Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions client/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 ');
Expand Down
12 changes: 10 additions & 2 deletions client/src/api/searchAlbums.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
85 changes: 46 additions & 39 deletions client/src/components/SearchForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<SearchForm query="" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
const input = screen.getByRole<HTMLInputElement>('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.
Expand All @@ -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(<SearchForm query="" onSearch={onSearch} />);
render(<SearchForm query="" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
type('Abbey');
view.rerender(<SearchForm query="Abbey" onSearch={onSearch} />);
advance(300);
expect(onSearch).not.toHaveBeenCalled();
const { rerender } = render(<SearchForm query="" onSearch={onSearch} />);
rerender(<SearchForm query="blue" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
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(<SearchForm query="" onSearch={onSearch} />);
type(' ');
submit();
expect(onSearch).toHaveBeenCalledExactlyOnceWith('');
});
});
24 changes: 11 additions & 13 deletions client/src/components/SearchForm.tsx
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof setTimeout> | 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 (
<form
className="search-form"
role="search"
onSubmit={(event) => {
event.preventDefault();
// Enter during a composition belongs to the IME, not to the form.
if (composing) return;

// Enter and the button bypass the delay without submitting twice.
clearTimeout(timer.current);
onSearch(draft.trim());
}}
>
Expand Down
33 changes: 24 additions & 9 deletions client/src/hooks/useAlbumSearch.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
import { useCallback, useRef, useState } from 'react';
import { useCallback, useMemo, useRef } from 'react';
import { skipToken, useQuery } from '@apollo/client/react';
import { NetworkStatus } from '@apollo/client';

import { SEARCH_ALBUMS } from '../api/searchAlbums.js';
import { SEARCH_ALBUMS, type AlbumSearchInput } from '../api/searchAlbums.js';
import { useSearchState } from './useSearchState.js';

const PAGE_SIZE = 20;

export function useAlbumSearch() {
const [query, setQuery] = useState('');
const { state, setQuery } = useSearchState();
const query = state.q;
const hasQuery = query.length > 0;
const retryInFlight = useRef(false);

// Apollo owns server data; React state only holds the committed search text.
// The input is derived from the URL rather than held in React state, so a
// reload or a shared link searches for the same thing. Any change to it drops
// the cursor: `after` is always null here, so #14 can never page across two
// different result sets.
const input = useMemo<AlbumSearchInput>(
() => ({
query,
sort: state.sort,
genreIds: state.genres.length > 0 ? state.genres : undefined,
decades: state.decades.length > 0 ? state.decades : undefined,
}),
[query, state.sort, state.genres, state.decades],
);

// Apollo owns server data; the URL owns what was asked for.
const { data, loading, error, refetch, networkStatus } = useQuery(
SEARCH_ALBUMS,
hasQuery
? { variables: { input: { query, sort: 'RELEVANCE' }, first: 20, after: null } }
: skipToken,
hasQuery ? { variables: { input, first: PAGE_SIZE, after: null } } : skipToken,
);

const retry = useCallback(() => {
Expand All @@ -38,10 +54,9 @@ export function useAlbumSearch() {
if (nextQuery !== query) setQuery(nextQuery);
else retry();
},
[query, retry],
[query, setQuery, retry],
);

// TODO(#6): Verify matching results against a populated database before accepting #9.
return {
query,
search,
Expand Down
Loading