('searchbox');
- input.focus();
- const defaultAllowed = fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });
- // jsdom needs the browser's implicit submission to be simulated explicitly.
- if (defaultAllowed) act(() => input.form?.requestSubmit());
- fireEvent.keyUp(input, { key: 'Enter', code: 'Enter' });
+ const input = screen.getByRole('combobox', {
+ name: 'Search by album or artist',
+ });
+ await user.click(input);
+ await user.keyboard('{Enter}');
expect(input).toHaveFocus();
} else {
- fireEvent.click(screen.getByRole('button', { name: 'Search' }));
+ await user.click(screen.getByRole('button', { name: 'Search' }));
}
expect(
@@ -386,7 +388,7 @@ describe('App search', () => {
expect(retry.parentElement).toBe(panel);
expect(retry).toHaveFocus();
await waitFor(() => expect(retry).toHaveAttribute('aria-disabled', 'true'));
- expect(screen.getByRole('status')).toHaveTextContent('Retrying search');
+ expect(resultStatus()).toHaveTextContent('Retrying search');
expect(screen.getByRole('region', { name: 'Search results' })).toHaveAttribute(
'aria-busy',
'true',
@@ -403,7 +405,7 @@ describe('App search', () => {
it('loads albums initially with labelled search and accessible landmarks', async () => {
renderApp([mockSearch('')]);
expect(
- screen.getByRole('searchbox', { name: 'Search by album or artist' }),
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
).toHaveValue('');
expect(screen.getByRole('main')).toHaveAttribute('id', 'main');
const hero = screen.getByRole('region', { name: 'Music worth holding onto.' });
@@ -417,7 +419,7 @@ describe('App search', () => {
expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue(
'RELEASE_YEAR_DESC',
);
- expect(screen.getByRole('status')).toHaveTextContent('Loading albums');
+ expect(resultStatus()).toHaveTextContent('Loading albums');
expect(screen.getByRole('combobox', { name: 'Sort by' })).toBeInTheDocument();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument();
@@ -428,13 +430,21 @@ describe('App search', () => {
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' } });
+ fireEvent.change(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ { target: { value: 'Abb' } },
+ );
+ fireEvent.change(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ { 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');
+ expect(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ ).toHaveValue('Abbey');
fireEvent.submit(screen.getByRole('search'));
await screen.findByRole('article', { name: 'Abbey Road' });
@@ -461,7 +471,9 @@ describe('App search', () => {
it('treats a pasted whitespace-only query as no query at all', async () => {
window.history.replaceState({}, '', '/?q=%20%20');
renderApp([mockSearch('')]);
- expect(screen.getByRole('searchbox')).toHaveValue('');
+ expect(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ ).toHaveValue('');
await screen.findByRole('article', { name: 'Abbey Road' });
expect(screen.getByRole('region', { name: 'Browse albums' })).toBeInTheDocument();
});
@@ -469,7 +481,7 @@ describe('App search', () => {
it('shows loading and then renders GraphQL result metadata after submission', async () => {
renderApp([mockSearch('Abbey')]);
submitSearch(' Abbey ');
- expect(screen.getByRole('status')).toHaveTextContent('Searching albums');
+ expect(resultStatus()).toHaveTextContent('Searching albums');
expect(screen.getAllByText('Searching albums…')).toHaveLength(1);
expect(
screen.queryByRole('button', { name: 'Retry search' }),
@@ -482,9 +494,7 @@ describe('App search', () => {
expect(within(card).getByText('Rock')).toBeInTheDocument();
expect(within(card).getByText('1,240 reviews')).toBeInTheDocument();
expect(card).toHaveTextContent('Average rating: 4.8 out of 5');
- expect(screen.getByRole('status')).toHaveTextContent(
- 'Showing 1 of 1 matching albums.',
- );
+ expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.');
});
it.each(['missing', ''])(
@@ -510,7 +520,9 @@ describe('App search', () => {
renderApp([empty, mockSearch('', [album], 'TITLE_DESC')]);
await screen.findByRole('heading', { name: 'No albums found' });
fireEvent.click(screen.getByRole('button', { name: 'Reset search' }));
- expect(screen.getByRole('searchbox')).toHaveValue('');
+ expect(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ ).toHaveValue('');
expect(window.location.search).toBe('?sort=TITLE_DESC');
expect(screen.getByRole('button', { name: 'Filters' })).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC');
@@ -545,7 +557,7 @@ describe('App search', () => {
submitSearch('Abbey');
expect(await screen.findByRole('alert')).toHaveTextContent('Could not load albums');
- expect(screen.getByRole('status')).toHaveTextContent('Search failed.');
+ expect(resultStatus()).toHaveTextContent('Search failed.');
expect(screen.queryByText('No albums found')).not.toBeInTheDocument();
expect(screen.queryByRole('article')).not.toBeInTheDocument();
@@ -555,9 +567,7 @@ describe('App search', () => {
await screen.findByRole('article', { name: 'Abbey Road' }),
).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
- expect(screen.getByRole('status')).toHaveTextContent(
- 'Showing 1 of 1 matching albums.',
- );
+ expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.');
});
it('re-queries the server when the sort changes and keeps it in the URL', async () => {
diff --git a/client/src/App.tsx b/client/src/App.tsx
index f6d7add..7c8ccbd 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -1,10 +1,11 @@
-import './App.css';
+import './App.css';
import SearchForm from './components/SearchForm.js';
import ResultsLayout from './components/ResultsLayout.js';
import { lazy, Suspense } from 'react';
import { useAlbumSearch } from './hooks/useAlbumSearch.js';
+import { useSearchHistory } from './hooks/useSearchHistory.js';
export default function App() {
const basePath = import.meta.env.BASE_URL.replace(/\/$/, '');
@@ -69,6 +70,12 @@ export default function App() {
function DiscoveryPage() {
const search = useAlbumSearch();
+ const history = useSearchHistory();
+
+ function submitSearch(query: string) {
+ search.search(query);
+ history.recordSearch(query);
+ }
return (
@@ -82,7 +89,7 @@ function DiscoveryPage() {
Search, rate and collect albums you’ll want to return to.
-
+
Photo by{' '}
diff --git a/client/src/a11y.test.tsx b/client/src/a11y.test.tsx
index a26fe2e..c2b81cd 100644
--- a/client/src/a11y.test.tsx
+++ b/client/src/a11y.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MockedProvider } from '@apollo/client/testing/react';
import type { MockLink } from '@apollo/client/testing';
@@ -7,6 +7,7 @@ import { GraphQLError } from 'graphql';
import axe from 'axe-core';
import App from './App.js';
+import { searchHistoryMocks } from './test/searchHistoryMocks.js';
import { SEARCH_ALBUMS } from './api/searchAlbums.js';
import type {
AlbumSummary,
@@ -56,19 +57,39 @@ function mockSearch(
};
}
-function renderApp(
+async function renderApp(
mocks: MockLink.MockedResponse[] = [],
) {
- return render(
-
+ const view = render(
+
,
);
+ await waitForQueries();
+ return view;
}
-function submitSearch(query: string) {
- fireEvent.change(screen.getByRole('searchbox'), { target: { value: query } });
- fireEvent.submit(screen.getByRole('search'));
+async function waitForQueries() {
+ // axe does not wrap React updates in act. Wait for album results and history,
+ // including the history refresh after a submitted search, before scanning.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('region', { name: /^(Browse albums|Search results)$/ }),
+ ).toHaveAttribute('aria-busy', 'false');
+ expect(
+ screen.getByRole('status', { name: 'Search history status' }),
+ ).not.toHaveTextContent('Loading recent searches');
+ });
+}
+
+async function submitSearch(query: string) {
+ const user = userEvent.setup();
+ await user.type(
+ screen.getByRole('combobox', { name: 'Search by album or artist' }),
+ query,
+ );
+ await user.click(screen.getByRole('button', { name: 'Search' }));
+ await waitForQueries();
}
/**
@@ -100,13 +121,13 @@ async function expectNoViolations(container: HTMLElement) {
describe('axe-core on the search page', () => {
it('is clean before anything is searched', async () => {
- const { container } = renderApp();
+ const { container } = await renderApp();
await expectNoViolations(container);
});
it('is clean with results rendered', async () => {
- const { container } = renderApp([mockSearch('Abbey')]);
- submitSearch('Abbey');
+ const { container } = await renderApp([mockSearch('Abbey')]);
+ await submitSearch('Abbey');
await screen.findByRole('region', { name: 'Search results' });
await waitFor(() =>
@@ -117,8 +138,8 @@ describe('axe-core on the search page', () => {
});
it('is clean with no results', async () => {
- const { container } = renderApp([mockSearch('zzzz', [])]);
- submitSearch('zzzz');
+ const { container } = await renderApp([mockSearch('zzzz', [])]);
+ await submitSearch('zzzz');
await screen.findByRole('heading', { name: 'No albums found' });
await expectNoViolations(container);
@@ -136,15 +157,15 @@ describe('axe-core on the search page', () => {
},
result: { errors: [new GraphQLError('Something went wrong')] },
};
- const { container } = renderApp([failing]);
- submitSearch('boom');
+ const { container } = await renderApp([failing]);
+ await submitSearch('boom');
await screen.findByText('Could not load albums. Please try again.');
await expectNoViolations(container);
});
it('is the first thing Tab reaches on the search page', async () => {
- renderApp();
+ await renderApp();
const user = userEvent.setup();
// One Tab from a fresh page has to land on the skip link. Checking that it
@@ -155,8 +176,8 @@ describe('axe-core on the search page', () => {
});
it('points the skip link at a target that exists and can take focus', async () => {
- renderApp([mockSearch('Abbey')]);
- submitSearch('Abbey');
+ await renderApp([mockSearch('Abbey')]);
+ await submitSearch('Abbey');
await screen.findByRole('region', { name: 'Search results' });
const skipLink = screen.getByRole('link', { name: 'Skip to content' });
@@ -169,7 +190,7 @@ describe('axe-core on the search page', () => {
// The target has to be programmatically focusable too, or the browser
// scrolls to it and leaves focus stranded back in the navigation.
- target!.focus();
+ act(() => target!.focus());
expect(target).toHaveFocus();
});
});
diff --git a/client/src/api/client.test.ts b/client/src/api/client.test.ts
index 0801752..7866446 100644
--- a/client/src/api/client.test.ts
+++ b/client/src/api/client.test.ts
@@ -1,9 +1,10 @@
import schemaSource from '../../../schema.graphql?raw';
import { buildSchema, validate } from 'graphql';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { cache } from './client.js';
import { SEARCH_ALBUMS } from './searchAlbums.js';
+import { MY_SEARCH_HISTORY } from './searchHistory.js';
import type {
AlbumSearchInput,
SearchAlbumsData,
@@ -65,6 +66,38 @@ it('validates the search operation against the repository schema', () => {
expect(validate(schema, SEARCH_ALBUMS)).toEqual([]);
});
+it('replaces complete history snapshots and clears them without affecting album results', () => {
+ const warn = vi.spyOn(console, 'warn');
+ try {
+ write(result(['1'], 'cursor-1'));
+ const albumsBefore = read();
+ const writeHistory = (queries: string[]) =>
+ cache.writeQuery({
+ query: MY_SEARCH_HISTORY,
+ data: {
+ mySearchHistory: queries.map((query) => ({
+ __typename: 'SearchHistoryEntry' as const,
+ query,
+ lastSearchedAt: '2026-11-13T12:00:00Z',
+ })),
+ },
+ });
+ writeHistory(['Blue', 'Abbey Road']);
+ writeHistory(['Abbey Road']);
+ expect(
+ cache
+ .readQuery({ query: MY_SEARCH_HISTORY })
+ ?.mySearchHistory.map((entry) => entry.query),
+ ).toEqual(['Abbey Road']);
+ writeHistory([]);
+ expect(cache.readQuery({ query: MY_SEARCH_HISTORY })?.mySearchHistory).toEqual([]);
+ expect(read()).toEqual(albumsBefore);
+ expect(warn).not.toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ }
+});
+
describe('searchAlbums cache policy', () => {
it('appends cursor pages, deduplicates normalized albums and updates metadata', () => {
write(result(['1', '2'], 'cursor-2'));
diff --git a/client/src/api/client.ts b/client/src/api/client.ts
index 8376513..2224901 100644
--- a/client/src/api/client.ts
+++ b/client/src/api/client.ts
@@ -23,6 +23,9 @@ export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
+ // Each response is the complete recent list, including [] after clear.
+ // Entries have no global IDs; replace this snapshot rather than merge it.
+ mySearchHistory: { merge: false },
searchAlbums: {
// Each complete search input gets its own list; paging arguments do not.
keyArgs: ['input'],
diff --git a/client/src/api/searchHistory.ts b/client/src/api/searchHistory.ts
new file mode 100644
index 0000000..a14796f
--- /dev/null
+++ b/client/src/api/searchHistory.ts
@@ -0,0 +1,25 @@
+import { graphql } from '../generated/gql.js';
+
+export const MY_SEARCH_HISTORY = graphql(`
+ query MySearchHistory {
+ mySearchHistory {
+ query
+ lastSearchedAt
+ }
+ }
+`);
+
+export const RECORD_SEARCH = graphql(`
+ mutation RecordSearch($query: String!) {
+ recordSearch(query: $query) {
+ query
+ lastSearchedAt
+ }
+ }
+`);
+
+export const CLEAR_SEARCH_HISTORY = graphql(`
+ mutation ClearSearchHistory {
+ clearSearchHistory
+ }
+`);
diff --git a/client/src/components/RecentSearches.css b/client/src/components/RecentSearches.css
new file mode 100644
index 0000000..52e48b3
--- /dev/null
+++ b/client/src/components/RecentSearches.css
@@ -0,0 +1,90 @@
+.recent-searches__popover {
+ position: absolute;
+ top: calc(100% + 0.5rem);
+ inset-inline: 0;
+ z-index: 1;
+}
+.recent-searches {
+ display: flex;
+ flex-direction: column;
+ max-height: min(18rem, 45dvh);
+ padding: 0.25rem;
+ border: 1px solid var(--border-strong);
+ border-radius: 5px;
+ background: var(--surface);
+ color: var(--text);
+ box-shadow: 0 0.75rem 2rem rgb(0 0 0 / 25%);
+}
+.recent-searches h2 {
+ margin: 0;
+ padding: 0.35rem 0.65rem;
+ font-size: 0.85rem;
+ color: var(--muted);
+}
+.recent-searches__list {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ padding: 0;
+ margin: 0;
+ list-style: none;
+}
+.recent-searches__header,
+.search-form .recent-searches__clear {
+ flex-shrink: 0;
+}
+.recent-searches__list li {
+ margin: 0;
+}
+.search-form .recent-searches button {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ width: 100%;
+ min-height: 2rem;
+ padding: 0.25rem 0.65rem;
+ border: 0;
+ background: transparent;
+ color: var(--text);
+ text-align: left;
+ white-space: normal;
+ overflow-wrap: anywhere;
+ font-weight: 400;
+}
+.recent-searches button svg {
+ flex-shrink: 0;
+ color: var(--muted);
+}
+.recent-searches button:hover {
+ background: var(--bg);
+ color: var(--accent);
+}
+.recent-searches [aria-selected='true'] {
+ background: var(--bg);
+ color: var(--accent);
+ box-shadow: inset 3px 0 var(--accent);
+}
+.recent-searches button:focus-visible {
+ outline: 3px solid var(--focus);
+ outline-offset: -3px;
+}
+.search-form .recent-searches__clear {
+ margin-top: 0.25rem;
+ border-top: 1px solid var(--border-strong);
+ border-radius: 0;
+ color: var(--accent);
+ font-size: 0.85rem;
+}
+.recent-searches__error {
+ padding: 0.75rem;
+ border: 1px solid var(--border-strong);
+ border-radius: 5px;
+ background: var(--surface);
+ color: var(--text);
+}
+@media (pointer: coarse) {
+ .search-form .recent-searches button {
+ min-height: 2.75rem;
+ }
+}
diff --git a/client/src/components/RecentSearches.test.tsx b/client/src/components/RecentSearches.test.tsx
new file mode 100644
index 0000000..33d984a
--- /dev/null
+++ b/client/src/components/RecentSearches.test.tsx
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import RecentSearches from './RecentSearches.js';
+
+const entries = [
+ { query: 'Blue', lastSearchedAt: '2026-11-10T12:00:00Z' },
+ { query: 'Abbey Road', lastSearchedAt: '2026-11-09T12:00:00Z' },
+];
+
+describe('RecentSearches', () => {
+ it('displays queries in the newest-first order provided by the server', () => {
+ render();
+ const region = screen.getByRole('region', { name: 'Recent searches' });
+ expect(within(region).getByRole('heading', { level: 2 })).toHaveTextContent(
+ 'Recent searches',
+ );
+ expect(
+ within(region)
+ .getAllByRole('option')
+ .map((item) => item.textContent),
+ ).toEqual(['Blue', 'Abbey Road']);
+ });
+
+ it('displays at most 10 entries', () => {
+ const manyEntries = Array.from({ length: 12 }, (_, index) => ({
+ query: `Query ${index}`,
+ lastSearchedAt: entries[0]!.lastSearchedAt,
+ }));
+ render();
+ expect(screen.getAllByRole('option')).toHaveLength(10);
+ expect(screen.queryByRole('option', { name: 'Query 10' })).not.toBeInTheDocument();
+ });
+
+ it('reports a selected query without clearing history', () => {
+ const onSelect = vi.fn();
+ const onClear = vi.fn();
+ render();
+ fireEvent.click(screen.getByRole('option', { name: 'Abbey Road' }));
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith('Abbey Road');
+ expect(onClear).not.toHaveBeenCalled();
+ });
+
+ it('reports clearing and hides the dropdown when history becomes empty', () => {
+ const onSelect = vi.fn();
+ const onClear = vi.fn();
+ const { rerender } = render(
+ ,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Clear recent searches' }));
+ expect(onClear).toHaveBeenCalledExactlyOnceWith();
+ expect(onSelect).not.toHaveBeenCalled();
+ rerender();
+ expect(screen.queryByText('No recent searches yet.')).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('region', { name: 'Recent searches' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Clear recent searches' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('keeps suggestions out of the tab order while clear remains keyboard accessible', async () => {
+ const user = userEvent.setup();
+ const onSelect = vi.fn();
+ const onClear = vi.fn();
+ const onSubmit = vi.fn((event) => event.preventDefault());
+ render(
+ ,
+ );
+ await user.tab();
+ expect(screen.getByRole('button', { name: 'Clear recent searches' })).toHaveFocus();
+ await user.keyboard(' ');
+ expect(onClear).toHaveBeenCalledOnce();
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/RecentSearches.tsx b/client/src/components/RecentSearches.tsx
new file mode 100644
index 0000000..dea8419
--- /dev/null
+++ b/client/src/components/RecentSearches.tsx
@@ -0,0 +1,122 @@
+import './RecentSearches.css';
+
+import { useId, useEffect } from 'react';
+
+interface Props {
+ /** Distinct queries in newest-first order, as returned by the server. */
+ entries: readonly { query: string; lastSearchedAt: string }[];
+ onSelect: (query: string) => void;
+ onClear: () => void;
+ loading?: boolean;
+ clearing?: boolean;
+ error?: string | null;
+ message?: string;
+ onRetry?: () => void;
+ id?: string;
+ open?: boolean;
+ activeIndex?: number;
+}
+
+export default function RecentSearches({
+ entries,
+ onSelect,
+ onClear,
+ loading = false,
+ clearing = false,
+ error,
+ message = '',
+ onRetry,
+ id,
+ open = true,
+ activeIndex = -1,
+}: Props) {
+ const headingId = useId();
+ const recent = entries.slice(0, 10);
+ const listId = id ?? headingId + '-list';
+
+ useEffect(() => {
+ if (open && activeIndex >= 0)
+ document
+ .getElementById(`${listId}-option-${activeIndex}`)
+ ?.scrollIntoView?.({ block: 'nearest' });
+ }, [open, activeIndex, listId]);
+
+ return (
+
+ {open && recent.length > 0 && (
+
+
+
Recent searches
+
+
+ {recent.map(({ query }, index) => (
+ -
+
+
+ ))}
+
+
+
+ )}
+
+ {error ??
+ (clearing
+ ? 'Clearing recent searches…'
+ : loading
+ ? 'Loading recent searches…'
+ : open && recent.length > 0
+ ? `${recent.length} recent searches available. Use the Up and Down arrow keys to choose, then Enter to search.`
+ : message)}
+
+ {error && onRetry && (
+
+ )}
+
+ );
+}
diff --git a/client/src/components/SearchForm.css b/client/src/components/SearchForm.css
index 967b3e8..7be5961 100644
--- a/client/src/components/SearchForm.css
+++ b/client/src/components/SearchForm.css
@@ -1,3 +1,7 @@
+.search-area {
+ max-width: 42.5rem;
+ min-width: 0;
+}
.search-form {
display: flex;
align-items: center;
@@ -11,6 +15,13 @@
box-shadow: 0 1.125rem 3.75rem rgb(0 0 0 / 32%);
}
/* Input focus belongs to the whole field; the button keeps its own focus ring. */
+.search-form__field {
+ position: relative;
+ display: flex;
+ align-items: center;
+ flex: 1;
+ min-width: 0;
+}
.search-form:has(input:focus-visible) {
outline: 3px solid var(--focus);
outline-offset: 4px;
diff --git a/client/src/components/SearchForm.test.tsx b/client/src/components/SearchForm.test.tsx
index 67688b3..73e8c1f 100644
--- a/client/src/components/SearchForm.test.tsx
+++ b/client/src/components/SearchForm.test.tsx
@@ -18,6 +18,33 @@ function advance(milliseconds: number) {
}
describe('SearchForm', () => {
+ it('restores the selected current query over a draft without losing focus', () => {
+ const onSearch = vi.fn();
+ render(
+ true,
+ }}
+ />,
+ );
+ const input = screen.getByRole('combobox', { name: 'Search by album or artist' });
+ act(() => input.focus());
+ fireEvent.change(input, { target: { value: 'Unsubmitted' } });
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onSearch).toHaveBeenCalledExactlyOnceWith('Blue');
+ expect(input).toHaveValue('Blue');
+ expect(input).toHaveFocus();
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ });
+
it('does not submit while typing', () => {
const onSearch = vi.fn();
render();
diff --git a/client/src/components/SearchForm.tsx b/client/src/components/SearchForm.tsx
index d0e148e..192a35b 100644
--- a/client/src/components/SearchForm.tsx
+++ b/client/src/components/SearchForm.tsx
@@ -1,71 +1,195 @@
-import './SearchForm.css';
+import './SearchForm.css';
-import { useState } from 'react';
+import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react';
+import RecentSearches from './RecentSearches.js';
interface Props {
query: string;
onSearch: (query: string) => void;
+ history?: {
+ entries: readonly { query: string; lastSearchedAt: string }[];
+ loading: boolean;
+ clearing: boolean;
+ error: string | null;
+ message: string;
+ retry?: () => void;
+ clearHistory: () => Promise;
+ };
}
-/**
- * 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) {
+/** Keeps the editable draft and suggestion interaction local; only explicit
+ * submissions reach the URL and history through onSearch. */
+export default function SearchForm({ query, onSearch, history }: Props) {
const [draft, setDraft] = useState(query);
const [previousQuery, setPreviousQuery] = useState(query);
const [composing, setComposing] = useState(false);
+ const [historyOpen, setHistoryOpen] = useState(false);
+ const [activeQuery, setActiveQuery] = useState(null);
+ const input = useRef(null);
+ const area = useRef(null);
+ const historyId = useId();
+ const recent = history?.entries.slice(0, 10) ?? [];
+ const expanded = historyOpen && recent.length > 0;
+ const activeIndex = expanded
+ ? recent.findIndex((entry) => entry.query === activeQuery)
+ : -1;
+ const hasHistory = Boolean(history);
- // 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.
+ // Back/forward and shared URLs update the draft without committing keystrokes.
if (query !== previousQuery) {
setPreviousQuery(query);
setDraft(query);
}
+ useEffect(() => {
+ if (!hasHistory) return;
+ function dismiss(event: PointerEvent) {
+ if (event.target instanceof Node && !area.current?.contains(event.target))
+ setHistoryOpen(false);
+ }
+ document.addEventListener('pointerdown', dismiss);
+ return () => document.removeEventListener('pointerdown', dismiss);
+ }, [hasHistory]);
+
+ function openHistory() {
+ setHistoryOpen(true);
+ setActiveQuery(null);
+ }
+
+ function closeHistory() {
+ setHistoryOpen(false);
+ setActiveQuery(null);
+ }
+
+ function submit(text: string) {
+ onSearch(text.trim());
+ closeHistory();
+ }
+
+ function select(query: string) {
+ // Reset even when the selected query already matches the URL.
+ setDraft(query);
+ input.current?.focus();
+ submit(query);
+ }
+
+ function navigate(event: KeyboardEvent) {
+ if (composing || event.nativeEvent.isComposing || event.keyCode === 229) return;
+ if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && recent.length > 0) {
+ event.preventDefault();
+ setHistoryOpen(true);
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
+ const start = activeIndex < 0 ? (direction === 1 ? -1 : 0) : activeIndex;
+ setActiveQuery(recent[(start + direction + recent.length) % recent.length]!.query);
+ } else if (event.key === 'Enter' && activeIndex >= 0) {
+ event.preventDefault();
+ select(recent[activeIndex]!.query);
+ }
+ }
+
+ async function clearHistory() {
+ const previousFocus = document.activeElement;
+ if (await history?.clearHistory()) {
+ // Restore focus without taking it back from someone who moved elsewhere.
+ if (
+ document.activeElement === previousFocus ||
+ document.activeElement === document.body
+ )
+ input.current?.focus();
+ closeHistory();
+ }
+ }
+
return (
-