From 4242e1c822d63e04077020c524df4ff70a0c6564 Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Mon, 19 Oct 2026 17:27:18 -0600 Subject: [PATCH 1/4] feat: #19 search state lives in the URL A reload, back/forward and a pasted link now reproduce the same result set, which is what the lecture's pitfall list calls out. `useSearchState` is the single owner of the four values that define a result set, and the query string is the authority rather than React state. `useAlbumSearch` derives its input from it instead of holding its own copy. Param names are the convention for the rest of the client, so #12 and #13 write through this hook rather than inventing their own: ?q=blue&sort=TITLE_ASC&genres=4&genres=7&decades=1970&decades=1990 Three decisions worth knowing about. **Lists are one param per value.** URLSearchParams percent encodes a comma into `%2C`, which turns a shared link into `?genres=4%2C7`. Parsing still accepts a comma joined list, since a hand-typed link can arrive in either shape. **Anything at its default is left out of the URL**, so a plain search is just `?q=blue`. And unknown params are carried through untouched, so adding a filter later cannot break a link someone already shared. **The cursor is deliberately absent.** #14 owns it, and the contract is that any change to these four values drops it. Because paging is never part of search state there is nothing here to carry across an input change, which is the property the acceptance line asks for. Two supporting changes. `ALBUM_SORTS` is now the runtime list behind the `AlbumSort` type, so URL parsing cannot drift from what the schema accepts. An unknown sort falls back to RELEVANCE rather than being sent to the server. `client/src/test/setup.ts` resets the URL around every test. The URL is application state now, so without it one test's search leaks into the next. That was the only test failure this change caused, and it was the test suite not isolating itself rather than the code being wrong. Co-Authored-By: opencode --- client/src/api/searchAlbums.ts | 12 +- client/src/hooks/useAlbumSearch.ts | 33 +++-- client/src/hooks/useSearchState.test.ts | 173 +++++++++++++++++++++++ client/src/hooks/useSearchState.ts | 180 ++++++++++++++++++++++++ client/src/test/setup.ts | 10 +- 5 files changed, 396 insertions(+), 12 deletions(-) create mode 100644 client/src/hooks/useSearchState.test.ts create mode 100644 client/src/hooks/useSearchState.ts 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/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index d2ef36d..de6ab01 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -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( + () => ({ + 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(() => { @@ -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, diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts new file mode 100644 index 0000000..8803718 --- /dev/null +++ b/client/src/hooks/useSearchState.test.ts @@ -0,0 +1,173 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + DEFAULT_SORT, + EMPTY_SEARCH_STATE, + parseSearchState, + serializeSearchState, + useSearchState, +} from './useSearchState.js'; + +function setUrl(url: string) { + window.history.replaceState({}, '', url); +} + +beforeEach(() => setUrl('/')); +afterEach(() => vi.restoreAllMocks()); + +describe('parseSearchState', () => { + it('returns the defaults for an empty query string', () => { + expect(parseSearchState('')).toEqual(EMPTY_SEARCH_STATE); + expect(parseSearchState('?')).toEqual(EMPTY_SEARCH_STATE); + }); + + it('reads every parameter', () => { + expect( + parseSearchState('?q=blue&sort=TITLE_ASC&genres=4,7&decades=1970,1990'), + ).toEqual({ + q: 'blue', + sort: 'TITLE_ASC', + genres: ['4', '7'], + decades: [1970, 1990], + }); + }); + + it('falls back to the default sort for a value the schema does not accept', () => { + expect(parseSearchState('?sort=TITLE_DESC').sort).toBe(DEFAULT_SORT); + expect(parseSearchState('?sort=').sort).toBe(DEFAULT_SORT); + expect(parseSearchState('?').sort).toBe(DEFAULT_SORT); + }); + + it('drops decades that are not integers', () => { + expect(parseSearchState('?decades=1970,abc,1990.5,,2000').decades).toEqual([ + 1970, 2000, + ]); + expect(parseSearchState('?decades=').decades).toEqual([]); + }); + + it('drops empty entries from a list', () => { + expect(parseSearchState('?genres=4,,7,').genres).toEqual(['4', '7']); + }); +}); + +describe('serializeSearchState', () => { + it('omits everything at its default so a plain search stays short', () => { + expect(serializeSearchState(EMPTY_SEARCH_STATE, '')).toBe(''); + }); + + it('writes only what differs from the default', () => { + expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, q: 'blue' }, '')).toBe( + '?q=blue', + ); + expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, sort: 'TITLE_ASC' }, '')).toBe( + '?sort=TITLE_ASC', + ); + expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, genres: ['4', '7'] }, '')).toBe( + '?genres=4&genres=7', + ); + expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, decades: [1970] }, '')).toBe( + '?decades=1970', + ); + }); + + it('accepts a comma joined list as well as repeated params', () => { + expect(parseSearchState('?genres=4,7').genres).toEqual(['4', '7']); + expect(parseSearchState('?genres=4&genres=7').genres).toEqual(['4', '7']); + expect(parseSearchState('?decades=1970,1990').decades).toEqual([1970, 1990]); + }); + + it('carries parameters it does not own through untouched', () => { + const out = serializeSearchState( + { ...EMPTY_SEARCH_STATE, q: 'blue' }, + '?utm_source=mail', + ); + expect(out).toContain('utm_source=mail'); + expect(out).toContain('q=blue'); + }); + + it('round-trips through parse', () => { + const state = { + q: 'blue', + sort: 'TITLE_ASC' as const, + genres: ['4'], + decades: [1970], + }; + expect(parseSearchState(serializeSearchState(state, ''))).toEqual(state); + }); +}); + +describe('useSearchState', () => { + it('reads the URL on first render', () => { + setUrl('/?q=blue&sort=TITLE_ASC'); + const { result } = renderHook(() => useSearchState()); + expect(result.current.state.q).toBe('blue'); + expect(result.current.state.sort).toBe('TITLE_ASC'); + }); + + it('writes a change to the URL and re-renders', () => { + const { result } = renderHook(() => useSearchState()); + + act(() => result.current.setQuery('blue')); + + expect(window.location.search).toBe('?q=blue'); + expect(result.current.state.q).toBe('blue'); + }); + + it('keeps the other values when one changes', () => { + setUrl('/?q=blue&genres=4&decades=1970'); + const { result } = renderHook(() => useSearchState()); + + act(() => result.current.setQuery('red')); + + expect(result.current.state).toEqual({ + q: 'red', + sort: DEFAULT_SORT, + genres: ['4'], + decades: [1970], + }); + expect(window.location.search).toContain('genres=4'); + expect(window.location.search).toContain('decades=1970'); + }); + + it('pushes a history entry for a real change but not for a no-op', () => { + const push = vi.spyOn(window.history, 'pushState'); + const { result } = renderHook(() => useSearchState()); + + act(() => result.current.setQuery('blue')); + expect(push).toHaveBeenCalledTimes(1); + + act(() => result.current.setQuery('blue')); + expect(push).toHaveBeenCalledTimes(1); + }); + + it('follows back and forward through popstate', () => { + const { result } = renderHook(() => useSearchState()); + + act(() => result.current.setQuery('blue')); + act(() => result.current.setQuery('red')); + expect(result.current.state.q).toBe('red'); + + // A browser back step restores the previous URL and fires popstate. + setUrl('/?q=blue'); + act(() => { + window.dispatchEvent(new PopStateEvent('popstate')); + }); + + expect(result.current.state.q).toBe('blue'); + }); + + it('drops the cursor implicitly, because state carries no paging value', () => { + const { result } = renderHook(() => useSearchState()); + act(() => result.current.setQuery('blue')); + + // The acceptance line for #19: any change goes back to page one. The cursor + // is never part of search state, so there is nothing here to carry over. + expect(Object.keys(result.current.state).sort()).toEqual([ + 'decades', + 'genres', + 'q', + 'sort', + ]); + }); +}); diff --git a/client/src/hooks/useSearchState.ts b/client/src/hooks/useSearchState.ts new file mode 100644 index 0000000..72d3d2c --- /dev/null +++ b/client/src/hooks/useSearchState.ts @@ -0,0 +1,180 @@ +import { useCallback, useSyncExternalStore } from 'react'; + +import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js'; + +/** + * Search state lives in the URL, so a reload, back and forward, and a pasted + * link all reproduce the same result set. The query string is the authority and + * React only mirrors it. + * + * Param names are the convention for the whole client. #12 adds the sort + * control and #13 the filter panel, and both write through here rather than + * inventing their own strings: + * + * ?q=blue&sort=TITLE_ASC&genres=4&genres=7&decades=1970&decades=1990 + * + * Lists are one param per value. Anything at its default is left out of the + * URL, so a plain search is just `?q=blue`. Parameters this hook does not own + * are preserved untouched, so adding one later cannot break a link someone + * already shared. + * + * Paging is deliberately absent. #14 owns the cursor, and the contract is that + * any change to these four values drops it, so the cursor is never written to + * the URL and never survives a change of input. + */ +export interface SearchState { + q: string; + sort: AlbumSort; + genres: string[]; + decades: number[]; +} + +export const DEFAULT_SORT: AlbumSort = 'RELEVANCE'; + +export const EMPTY_SEARCH_STATE: SearchState = { + q: '', + sort: DEFAULT_SORT, + genres: [], + decades: [], +}; + +/** Param names. Import these rather than repeating string literals. */ +export const SEARCH_PARAMS = { + q: 'q', + sort: 'sort', + genres: 'genres', + decades: 'decades', +} as const; + +function isAlbumSort(value: string | null): value is AlbumSort { + return value !== null && (ALBUM_SORTS as readonly string[]).includes(value); +} + +function parseValues(params: URLSearchParams, key: string): string[] { + // Accept both `?genres=4&genres=7` and a hand-edited `?genres=4,7`, since + // either can turn up in a link someone typed or got from elsewhere. + return params + .getAll(key) + .flatMap((value) => value.split(',')) + .filter((part) => part.length > 0); +} + +/** + * Parse a query string into search state. Anything unrecognised falls back to + * the default rather than being passed on, so a hand-edited link cannot send a + * value the schema would reject. + */ +export function parseSearchState(search: string): SearchState { + const params = new URLSearchParams(search); + const sort = params.get(SEARCH_PARAMS.sort); + const decades = parseValues(params, SEARCH_PARAMS.decades) + .map(Number) + .filter(Number.isInteger); + + return { + q: params.get(SEARCH_PARAMS.q) ?? '', + sort: isAlbumSort(sort) ? sort : DEFAULT_SORT, + genres: parseValues(params, SEARCH_PARAMS.genres), + decades, + }; +} + +/** + * Write search state back into a query string. Params this hook does not own + * are carried over from `currentSearch` unchanged. + */ +export function serializeSearchState(state: SearchState, currentSearch: string): string { + const params = new URLSearchParams(currentSearch); + + params.delete(SEARCH_PARAMS.q); + params.delete(SEARCH_PARAMS.sort); + params.delete(SEARCH_PARAMS.genres); + params.delete(SEARCH_PARAMS.decades); + + if (state.q) params.set(SEARCH_PARAMS.q, state.q); + if (state.sort !== DEFAULT_SORT) params.set(SEARCH_PARAMS.sort, state.sort); + // One param per value rather than a comma joined list. URLSearchParams + // percent encodes a comma into `%2C`, which makes a shared link unreadable. + for (const genre of state.genres) params.append(SEARCH_PARAMS.genres, genre); + for (const decade of state.decades) + params.append(SEARCH_PARAMS.decades, String(decade)); + + const query = params.toString(); + return query ? `?${query}` : ''; +} + +type Listener = () => void; + +const listeners = new Set(); +let popstateBound = false; + +// Cached by the query string so getSnapshot returns a stable object and React +// does not re-render on every call. +let cachedSearch: string | null = null; +let cachedState: SearchState = EMPTY_SEARCH_STATE; + +function readSearchState(): SearchState { + const search = window.location.search; + if (search !== cachedSearch) { + cachedSearch = search; + cachedState = parseSearchState(search); + } + return cachedState; +} + +function notify(): void { + for (const listener of listeners) listener(); +} + +function subscribe(listener: Listener): () => void { + if (!popstateBound) { + window.addEventListener('popstate', notify); + popstateBound = true; + } + listeners.add(listener); + + return () => { + listeners.delete(listener); + if (listeners.size === 0) { + window.removeEventListener('popstate', notify); + popstateBound = false; + } + }; +} + +function writeSearchState(next: SearchState): void { + const current = window.location.search; + const search = serializeSearchState(next, current); + // No history entry when nothing actually changes. + if (search === current) return; + + const url = `${window.location.pathname}${search}${window.location.hash}`; + window.history.pushState(window.history.state, '', url); + + cachedSearch = search; + cachedState = parseSearchState(search); + notify(); +} + +/** + * The four values that define a result set, plus the setters that keep the URL + * in step. Each setter pushes a history entry, so back and forward step through + * the searches the way a user expects. + */ +export function useSearchState() { + const state = useSyncExternalStore(subscribe, readSearchState, readSearchState); + + const setSearch = useCallback((patch: Partial) => { + writeSearchState({ ...readSearchState(), ...patch }); + }, []); + + const setQuery = useCallback((q: string) => setSearch({ q }), [setSearch]); + const setSort = useCallback((sort: AlbumSort) => setSearch({ sort }), [setSearch]); + const setGenres = useCallback((genres: string[]) => setSearch({ genres }), [setSearch]); + const setDecades = useCallback( + (decades: number[]) => setSearch({ decades }), + [setSearch], + ); + + return { state, setQuery, setSort, setGenres, setDecades }; +} diff --git a/client/src/test/setup.ts b/client/src/test/setup.ts index 0d74b73..4f41d02 100644 --- a/client/src/test/setup.ts +++ b/client/src/test/setup.ts @@ -1,7 +1,15 @@ import '@testing-library/jest-dom/vitest'; import { cleanup } from '@testing-library/react'; -import { afterEach } from 'vitest'; +import { afterEach, beforeEach } from 'vitest'; + +// The URL is application state, not a browser detail: useSearchState reads it +// and writes it. Tests render a mounted app, so each one has to start from a +// known query string or the previous test's search leaks into the next. +beforeEach(() => { + window.history.replaceState({}, '', '/'); +}); afterEach(() => { cleanup(); + window.history.replaceState({}, '', '/'); }); From 5f20ea5434de6efda1a9b4f54d60843f64d5cf3a Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Mon, 19 Oct 2026 17:37:37 -0600 Subject: [PATCH 2/4] fix: #19 only write the query to the URL on Search Typing was committing on a 300 ms debounce, so the URL rewrote itself while someone was mid-word. That is the opposite of what the URL is supposed to be for: it is a permalink to a result set, not a live mirror of a text box. It also had a visible symptom. The write re-rendered SearchForm, and the `query !== previousQuery` branch then reset the draft back to the committed value, so text typed in the same instant was thrown away. It read as the page reloading on every keystroke. Now typing only edits a local draft. The query reaches the URL and the network when the form is submitted, by the button or by Enter. Consequences worth naming. **The debounce is gone**, and with it the timer and the cleanup effect. #18 lists "debounce + cache-first fetch policy (no wasted requests)" as a sustainability measure. Submit-only is a stronger version of that: zero requests while typing rather than one per pause. The word debounce no longer applies and #18 should be reworded. **IME composition is now guarded at submit** rather than by deferring the timer. Enter during a composition belongs to the composer. **External changes still reach the input.** Back/forward and a pasted link move the URL without the form being involved, and the box has to follow them. That branch stays; what changed is that typing can no longer fall into it, because typing does not change the query any more. SearchForm.test.tsx is rewritten against the new contract. The old suite asserted the debounce, so it asserted the behaviour being removed. Co-Authored-By: opencode --- client/src/App.test.tsx | 16 +++++ client/src/components/SearchForm.test.tsx | 85 ++++++++++++----------- client/src/components/SearchForm.tsx | 24 +++---- 3 files changed, 73 insertions(+), 52 deletions(-) diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 1ba7ae4..7177db9 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -163,6 +163,22 @@ 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('shows loading and then renders GraphQL result metadata after submission', async () => { renderApp([mockSearch('Abbey')]); submitSearch(' Abbey '); 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 (
{ 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()); }} > From 747d8202fed755074383df26d8e26278261221d6 Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Mon, 19 Oct 2026 17:44:27 -0600 Subject: [PATCH 3/4] docs: #48 add AI usage rows for 19 October Three erikhfj rows: the M3 issue distribution and the six issues whose text contradicted the schema or the identity contract, the review of #53 against the code, and #19 with the submit-only correction. Co-Authored-By: opencode --- docs/AI-USAGE.md | 95 +++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 46 deletions(-) diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 5e08f4d..d5cbdd8 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -9,52 +9,55 @@ Everyone adds their own rows. Two rows in the middle have no tool in them on purpose: they are where a person overruled what the tool proposed, which is the part that matters most. -| Date | Who | Tool | Used for | -| ---------- | -------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 2026-09-23 | erikhfj | opencode | Stack prototype (PostgreSQL, GraphQL Yoga, Drizzle, React + Apollo) to answer two design risks early: does Postgres FTS give case-insensitive single-term search, and does keyset paging stay correct across every sort mode. Verified live on the VM. **Closed unmerged**, kept as `archive/scaffold-prototype`. | -| 2026-09-23 | erikhfj | opencode | VM bootstrap scripts: PostgreSQL role and database, Node 24 via nvm, `crate-api` systemd unit, Apache `ProxyPass /graphql` | -| 2026-09-23 | erikhfj | opencode | Smoke tests against the running API. These caught three bugs the unit tests had missed: `GenreFacet.genre` shape drift from the SDL, drizzle expanding a JS array into scalar parameters inside a `::int[]` cast, and a missing review aggregate on `album(id:)` | -| 2026-09-24 | erikhfj | opencode | Plan to retire the prototype PR and re-land the work in milestone-sized PRs | -| 2026-09-24 | rachelks | - | **Overruled the plan.** Splitting generated code into smaller PRs would only fix the git cosmetics, so each issue must be implemented from its requirements by its owner. The prototype is a reference, not a source to copy from. Taken. | -| 2026-09-24 | robertky | - | **Overruled the plan.** Dropped the plan-before-code step as process for its own sake; clear issues plus PR descriptions that say what was done and tested are what reviewers read. Also: assign issues one milestone at a time, not all up front. Taken. | -| 2026-09-27 | rachelks | Codex (ChatGPT) | Discussed the UI specification for #29 and how to translate the project requirements into the planned interface. I reviewed and adapted the specification to the group's agreed design. | -| 2026-09-27 | robertky | Codex (ChatGPT) | Assisted with drafting the M1 GraphQL schema and data model for #2. I reviewed the model, kept database/resolvers out of M1, and incorporated peer-review feedback before merge. | -| 2026-09-28 | erikhfj | opencode | Tooling for #1: pnpm workspace, ESLint 9 flat config, Prettier, strict TypeScript, `AGENTS.md` | -| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing #32 and diagnosing a Windows-specific formatting failure. Testing with `core.autocrlf=true` exposed the LF/CRLF issue; I reported it in the review and erikhfj fixed it with `.gitattributes` before merge. | -| 2026-09-28 | erikhfj | opencode | Review fix for #1: `.gitattributes` with `* text=auto eol=lf` after `core.autocrlf` broke `pnpm format:check` on Windows | -| 2026-09-28 | erikhfj | opencode | Workflow guide and this log for #4 | -| 2026-09-28 | evenkkl | Claude | Assisted with formulating a schema for the architecture decision in #3, and served as a sparring partner to help understand why we made the decisions we did. | -| 2026-09-28 | erikhfj | opencode | CI for #27: `quality` and `deploy` jobs, self-hosted runner registered on the VM, client bundle budget | -| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing the CI workflow in #34. Identified that the `project2` runner label was not used by the deploy job. I reported it in the review, erikhfj then pinned the deploy job to the intended runner. | -| 2026-09-29 | erikhfj | opencode | Review fix for #27: `pull_request` no longer filters on `branches: [main]`, which had silently given stacked PRs zero CI runs | -| 2026-09-30 | rachelks | Codex (ChatGPT) | Assisted with reviewing the GraphQL schema in #35. I identified a missing paginated review connection required by the specification and requested changes; robertky corrected the schema before merge. | -| 2026-09-30 | robertky | Codex (ChatGPT) | Helped me interpret Rachel's schema review on #35. | -| 2026-09-30 | evenkkl | Claude | Assisted with formulating reviews of PR #35, and identifying additional areas for improvement. | -| 2026-10-01 | erikhfj | opencode | Answers to the open design questions: UUID as an `X-User-Id` header into the GraphQL context, narrowing facet counts, `id` tie-breakers, nulls last in both directions | -| 2026-10-01 | rachelks | Codex (ChatGPT) | Assisted with diagnosing the CI deploy failure after merge. The investigation traced the API restart issue to the `crate-api.service` check, `sudo` requiring a TTY, and a race while waiting for the API to start; erikhfj then fixed the deploy workflow. | -| 2026-10-01 | erikhfj | opencode | CI deploy fix for #27 after rachelks reported it: `grep -q` SIGPIPE silently skipped a live service, `sudo` had no TTY, and `sleep 2` raced Node binding the port. All three verified against the live unit | -| 2026-10-01 | erikhfj | opencode | Simplified this log to a table at the group's request | -| 2026-10-01 | robertky | Codex (ChatGPT) | Assisted with formulating good reviews of the architecture and UI-specification PRs. The group decided to include decade filtering; Rachel implemented the corresponding schema and documentation update in #38. | -| 2026-10-07 | erikhfj | opencode | Simulated user identity for #10: a `User` type and the `X-User-Id` header contract, read into a per-request GraphQL context so that no field in `schema.graphql` takes a `userId` argument | -| 2026-10-07 | rachelks | ChatGPT | Assisted with frontend styling, UI decisions and troubleshooting for #9 (PR #47). | -| 2026-10-09 | robertky | Codex (ChatGPT) | AI was a good sparring partner when I drafted the initial #5 PostgreSQL migration. It gave me ideas on how to structure and improve the tables, relation tables, constraints, indexes, full-text search triggers and TypeScript migration runner. | -| 2026-10-09 | erikhfj | opencode | VM runbook for #8, and converted `~/T19-Project-2` from a hand-copied prototype into a real git clone of `main` with a deploy SSH key. The gitignored `.env` was checksummed across `git checkout --force` to prove a deploy does not wipe `DATABASE_URL` | -| 2026-10-10 | evenkkl | Claude | Assisted with implementing the GraphQL Yoga server with `searchAlbums` for #6, and formulated an easy to understand PR description. Guided the reset of the prototype tables in the VM database (backup taken first). | -| 2026-10-10 | erikhfj | opencode | Wrote out the facet-count trade-off on #13: OR within a category pairs with per-dimension exclusion, AND with global counts. Posted as an analysis for the group to settle, not as a decision | -| 2026-10-10 | erikhfj | opencode | Forced `source-map-js` to 1.2.2 through `pnpm.overrides` for #43, after the Dependabot alert | -| 2026-10-10 | rachelks | ChatGPT | Assisted with reviewing PR #42, identifying an issue with the backend deployment workflow that led to #44. | -| 2026-10-10 | erikhfj | opencode | Traced the deploy gap rachelks raised on #42 and opened #44: CI built `server/` in the runner workspace while `crate-api.service` runs `dist/index.js` out of `~/T19-Project-2/server`, so a restart kept bringing back a 23 September prototype | -| 2026-10-12 | erikhfj | opencode | **Tool output corrected by a person.** The draft identity contract said `displayName`, derived server-side from the UUID, stops one user writing as another. It does not: the client can still send any UUID. robertky caught it on review and the wording was fixed in #40 | -| 2026-10-13 | evenkkl | Claude | Fixed the review feedback on #6: cursor values validated against the sort, `reviewCount` returns 0 until reviews exist. The group decided genre filters combine with AND; Claude made the filter and the genre counts match that. | -| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing PRs #45 and #46, identifying issues with deployment checks, database migrations and FTS triggers. Erik and Robert addressed the issues before merging. | -| 2026-10-15 | erikhfj | opencode | Rachel's four review points on #45: the smoke query omitted the required `sort` field so it could never have passed, the deploy step skipped instead of failing, and the body check grepped for the word "errors" instead of parsing JSON. Two bugs in my own first attempt: a multi-line `python3 -c` cannot live inside a YAML block scalar, and `\"` in bash single quotes is a literal backslash | -| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing M2 documentation for #48, identifying outdated setup instructions and missing frontend information. | -| 2026-10-15 | erikhfj | opencode | Documentation pass for #48: this log and the README brought up to date with what has actually landed | -| 2026-10-15 | erikhfj | opencode | Folded #46 into the README, and added `db:migrate` to the deploy on #45 after #46 pointed out it never ran: a deploy that lands migration files without applying them leaves the schema behind the code. Also reconciled `DATABASE_URL`, which the systemd unit reads from the checkout root and the server package scripts read from `server/.env` | -| 2026-10-15 | robertky | Codex (ChatGPT) | Assisted me when I designed and implemented #7's batched synthetic catalog generator, its tests and local performance verification. I reviewed the generated data, when AI suggested something before using it. | -| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with updating README and VM setup documentation for #48, clarifying implemented functionality and local development instructions. | -| 2026-10-16 | evenkkl | Claude | Assisted with reviewing PRs #50 and #51, checking the changes against the code and identifying areas for improvement. | -| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with a final documentation review and cleanup for #48. | +| Date | Who | Tool | Used for | +| ---------- | -------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2026-09-23 | erikhfj | opencode | Stack prototype (PostgreSQL, GraphQL Yoga, Drizzle, React + Apollo) to answer two design risks early: does Postgres FTS give case-insensitive single-term search, and does keyset paging stay correct across every sort mode. Verified live on the VM. **Closed unmerged**, kept as `archive/scaffold-prototype`. | +| 2026-09-23 | erikhfj | opencode | VM bootstrap scripts: PostgreSQL role and database, Node 24 via nvm, `crate-api` systemd unit, Apache `ProxyPass /graphql` | +| 2026-09-23 | erikhfj | opencode | Smoke tests against the running API. These caught three bugs the unit tests had missed: `GenreFacet.genre` shape drift from the SDL, drizzle expanding a JS array into scalar parameters inside a `::int[]` cast, and a missing review aggregate on `album(id:)` | +| 2026-09-24 | erikhfj | opencode | Plan to retire the prototype PR and re-land the work in milestone-sized PRs | +| 2026-09-24 | rachelks | - | **Overruled the plan.** Splitting generated code into smaller PRs would only fix the git cosmetics, so each issue must be implemented from its requirements by its owner. The prototype is a reference, not a source to copy from. Taken. | +| 2026-09-24 | robertky | - | **Overruled the plan.** Dropped the plan-before-code step as process for its own sake; clear issues plus PR descriptions that say what was done and tested are what reviewers read. Also: assign issues one milestone at a time, not all up front. Taken. | +| 2026-09-27 | rachelks | Codex (ChatGPT) | Discussed the UI specification for #29 and how to translate the project requirements into the planned interface. I reviewed and adapted the specification to the group's agreed design. | +| 2026-09-27 | robertky | Codex (ChatGPT) | Assisted with drafting the M1 GraphQL schema and data model for #2. I reviewed the model, kept database/resolvers out of M1, and incorporated peer-review feedback before merge. | +| 2026-09-28 | erikhfj | opencode | Tooling for #1: pnpm workspace, ESLint 9 flat config, Prettier, strict TypeScript, `AGENTS.md` | +| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing #32 and diagnosing a Windows-specific formatting failure. Testing with `core.autocrlf=true` exposed the LF/CRLF issue; I reported it in the review and erikhfj fixed it with `.gitattributes` before merge. | +| 2026-09-28 | erikhfj | opencode | Review fix for #1: `.gitattributes` with `* text=auto eol=lf` after `core.autocrlf` broke `pnpm format:check` on Windows | +| 2026-09-28 | erikhfj | opencode | Workflow guide and this log for #4 | +| 2026-09-28 | evenkkl | Claude | Assisted with formulating a schema for the architecture decision in #3, and served as a sparring partner to help understand why we made the decisions we did. | +| 2026-09-28 | erikhfj | opencode | CI for #27: `quality` and `deploy` jobs, self-hosted runner registered on the VM, client bundle budget | +| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing the CI workflow in #34. Identified that the `project2` runner label was not used by the deploy job. I reported it in the review, erikhfj then pinned the deploy job to the intended runner. | +| 2026-09-29 | erikhfj | opencode | Review fix for #27: `pull_request` no longer filters on `branches: [main]`, which had silently given stacked PRs zero CI runs | +| 2026-09-30 | rachelks | Codex (ChatGPT) | Assisted with reviewing the GraphQL schema in #35. I identified a missing paginated review connection required by the specification and requested changes; robertky corrected the schema before merge. | +| 2026-09-30 | robertky | Codex (ChatGPT) | Helped me interpret Rachel's schema review on #35. | +| 2026-09-30 | evenkkl | Claude | Assisted with formulating reviews of PR #35, and identifying additional areas for improvement. | +| 2026-10-01 | erikhfj | opencode | Answers to the open design questions: UUID as an `X-User-Id` header into the GraphQL context, narrowing facet counts, `id` tie-breakers, nulls last in both directions | +| 2026-10-01 | rachelks | Codex (ChatGPT) | Assisted with diagnosing the CI deploy failure after merge. The investigation traced the API restart issue to the `crate-api.service` check, `sudo` requiring a TTY, and a race while waiting for the API to start; erikhfj then fixed the deploy workflow. | +| 2026-10-01 | erikhfj | opencode | CI deploy fix for #27 after rachelks reported it: `grep -q` SIGPIPE silently skipped a live service, `sudo` had no TTY, and `sleep 2` raced Node binding the port. All three verified against the live unit | +| 2026-10-01 | erikhfj | opencode | Simplified this log to a table at the group's request | +| 2026-10-01 | robertky | Codex (ChatGPT) | Assisted with formulating good reviews of the architecture and UI-specification PRs. The group decided to include decade filtering; Rachel implemented the corresponding schema and documentation update in #38. | +| 2026-10-07 | erikhfj | opencode | Simulated user identity for #10: a `User` type and the `X-User-Id` header contract, read into a per-request GraphQL context so that no field in `schema.graphql` takes a `userId` argument | +| 2026-10-07 | rachelks | ChatGPT | Assisted with frontend styling, UI decisions and troubleshooting for #9 (PR #47). | +| 2026-10-09 | robertky | Codex (ChatGPT) | AI was a good sparring partner when I drafted the initial #5 PostgreSQL migration. It gave me ideas on how to structure and improve the tables, relation tables, constraints, indexes, full-text search triggers and TypeScript migration runner. | +| 2026-10-09 | erikhfj | opencode | VM runbook for #8, and converted `~/T19-Project-2` from a hand-copied prototype into a real git clone of `main` with a deploy SSH key. The gitignored `.env` was checksummed across `git checkout --force` to prove a deploy does not wipe `DATABASE_URL` | +| 2026-10-10 | evenkkl | Claude | Assisted with implementing the GraphQL Yoga server with `searchAlbums` for #6, and formulated an easy to understand PR description. Guided the reset of the prototype tables in the VM database (backup taken first). | +| 2026-10-10 | erikhfj | opencode | Wrote out the facet-count trade-off on #13: OR within a category pairs with per-dimension exclusion, AND with global counts. Posted as an analysis for the group to settle, not as a decision | +| 2026-10-10 | erikhfj | opencode | Forced `source-map-js` to 1.2.2 through `pnpm.overrides` for #43, after the Dependabot alert | +| 2026-10-10 | rachelks | ChatGPT | Assisted with reviewing PR #42, identifying an issue with the backend deployment workflow that led to #44. | +| 2026-10-10 | erikhfj | opencode | Traced the deploy gap rachelks raised on #42 and opened #44: CI built `server/` in the runner workspace while `crate-api.service` runs `dist/index.js` out of `~/T19-Project-2/server`, so a restart kept bringing back a 23 September prototype | +| 2026-10-12 | erikhfj | opencode | **Tool output corrected by a person.** The draft identity contract said `displayName`, derived server-side from the UUID, stops one user writing as another. It does not: the client can still send any UUID. robertky caught it on review and the wording was fixed in #40 | +| 2026-10-13 | evenkkl | Claude | Fixed the review feedback on #6: cursor values validated against the sort, `reviewCount` returns 0 until reviews exist. The group decided genre filters combine with AND; Claude made the filter and the genre counts match that. | +| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing PRs #45 and #46, identifying issues with deployment checks, database migrations and FTS triggers. Erik and Robert addressed the issues before merging. | +| 2026-10-15 | erikhfj | opencode | Rachel's four review points on #45: the smoke query omitted the required `sort` field so it could never have passed, the deploy step skipped instead of failing, and the body check grepped for the word "errors" instead of parsing JSON. Two bugs in my own first attempt: a multi-line `python3 -c` cannot live inside a YAML block scalar, and `\"` in bash single quotes is a literal backslash | +| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing M2 documentation for #48, identifying outdated setup instructions and missing frontend information. | +| 2026-10-15 | erikhfj | opencode | Documentation pass for #48: this log and the README brought up to date with what has actually landed | +| 2026-10-15 | erikhfj | opencode | Folded #46 into the README, and added `db:migrate` to the deploy on #45 after #46 pointed out it never ran: a deploy that lands migration files without applying them leaves the schema behind the code. Also reconciled `DATABASE_URL`, which the systemd unit reads from the checkout root and the server package scripts read from `server/.env` | +| 2026-10-15 | robertky | Codex (ChatGPT) | Assisted me when I designed and implemented #7's batched synthetic catalog generator, its tests and local performance verification. I reviewed the generated data, when AI suggested something before using it. | +| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with updating README and VM setup documentation for #48, clarifying implemented functionality and local development instructions. | +| 2026-10-16 | evenkkl | Claude | Assisted with reviewing PRs #50 and #51, checking the changes against the code and identifying areas for improvement. | +| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with a final documentation review and cleanup for #48. | +| 2026-10-19 | erikhfj | opencode | Distributed the M3 issues #11 to #19 across the four of us, then corrected six of them where the text contradicted `schema.graphql` or the M2 identity contract: `toggleCrate` and `inCrate(userId:)` do not exist, `AlbumSort` uses `RELEASE_YEAR` and `AVERAGE_RATING` rather than `YEAR` and `RATING`, `countries` duplicates #25, and the genre facet counts do not exclude their own dimension the way the decade counts do. | +| 2026-10-19 | erikhfj | opencode | Reviewed #53 against the code rather than as prose. Found the README contradicting its own Implemented section and a smoke test that dropped an expectation while keeping the field in the query. Verified Rachel's other claims, including that `AVERAGE_RATING_DESC` throws, which corrected my own "four sort modes" in the README. | +| 2026-10-19 | erikhfj | opencode | Search state in the URL for #19, with `useSearchState` owning `q`, `sort`, `genres` and `decades`. My first version committed on a 300 ms debounce, which rewrote the URL mid-word and reset the input back through the `query !== previousQuery` branch; it read as the page reloading on every keystroke. Changed so the query reaches the URL only on Search. | ## Notes From d6df6da628042afe12b6c89f086b1c650f0b599f Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Tue, 20 Oct 2026 11:41:11 -0600 Subject: [PATCH 4/4] fix: #19 reject junk URL values instead of sending them on Robert: a pasted ?q=%20%20 made the client treat the search as active while the server trimmed it to nothing, and ?genres=rock reached the backend even though the comment promised invalid values never do. Both were real. parseSearchState now trims q, so whitespace-only is an empty search rather than an active one. Genre ids are filtered to integers on the way in and on the way out, mirroring parseGenreId in server/src/search/ search.ts, which throws Invalid genre id for anything else. Doing it on both sides means the URL can never carry one the server would reject however the state was built. decades was already filtered the same way and needed nothing. Regression tests cover both cases plus the serialize side. Co-Authored-By: opencode --- client/src/App.test.tsx | 14 +++++++++++++ client/src/hooks/useSearchState.test.ts | 24 +++++++++++++++++++++++ client/src/hooks/useSearchState.ts | 26 +++++++++++++++++++++---- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 7177db9..84dbfb6 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -179,6 +179,20 @@ describe('App search', () => { 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/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts index 8803718..561d365 100644 --- a/client/src/hooks/useSearchState.test.ts +++ b/client/src/hooks/useSearchState.test.ts @@ -49,6 +49,22 @@ describe('parseSearchState', () => { it('drops empty entries from a list', () => { expect(parseSearchState('?genres=4,,7,').genres).toEqual(['4', '7']); }); + + it('treats a whitespace-only query as an empty search', () => { + // A pasted `?q=%20%20` used to count as an active query while the server + // trimmed it to nothing, so the client searched and got an empty result. + expect(parseSearchState('?q=%20%20').q).toBe(''); + expect(parseSearchState('?q=%20%20')).toEqual(EMPTY_SEARCH_STATE); + expect(parseSearchState('?q=+blue+').q).toBe('blue'); + }); + + it('drops genre ids the server would reject', () => { + // `parseGenreId` on the server throws `Invalid genre id` for a value that is + // not an integer, so these must never reach it. + expect(parseSearchState('?genres=rock').genres).toEqual([]); + expect(parseSearchState('?genres=%20').genres).toEqual([]); + expect(parseSearchState('?genres=rock,4,seven,7').genres).toEqual(['4', '7']); + }); }); describe('serializeSearchState', () => { @@ -77,6 +93,14 @@ describe('serializeSearchState', () => { expect(parseSearchState('?decades=1970,1990').decades).toEqual([1970, 1990]); }); + it('never writes a value the server would reject', () => { + const out = serializeSearchState( + { q: ' ', sort: DEFAULT_SORT, genres: ['rock', '4', ''], decades: [1970] }, + '', + ); + expect(out).toBe('?genres=4&decades=1970'); + }); + it('carries parameters it does not own through untouched', () => { const out = serializeSearchState( { ...EMPTY_SEARCH_STATE, q: 'blue' }, diff --git a/client/src/hooks/useSearchState.ts b/client/src/hooks/useSearchState.ts index 72d3d2c..11b1c27 100644 --- a/client/src/hooks/useSearchState.ts +++ b/client/src/hooks/useSearchState.ts @@ -59,10 +59,24 @@ function parseValues(params: URLSearchParams, key: string): string[] { .filter((part) => part.length > 0); } +/** + * Mirrors `parseGenreId` in `server/src/search/search.ts`, which rejects a value + * that is not an integer with `Invalid genre id`. Dropping those here keeps a + * hand-edited link from turning into a GraphQL error. Empty after trimming goes + * too, so `?genres=%20` is not treated as a genre. + */ +function isGenreId(value: string): boolean { + return value.trim().length > 0 && Number.isInteger(Number(value)); +} + /** * Parse a query string into search state. Anything unrecognised falls back to * the default rather than being passed on, so a hand-edited link cannot send a * value the schema would reject. + * + * `q` is trimmed here as well as at submission. A pasted `?q=%20%20` is an + * empty search, not an active one: without this the client would consider + * there to be a query while the server trimmed it to nothing. */ export function parseSearchState(search: string): SearchState { const params = new URLSearchParams(search); @@ -72,9 +86,9 @@ export function parseSearchState(search: string): SearchState { .filter(Number.isInteger); return { - q: params.get(SEARCH_PARAMS.q) ?? '', + q: (params.get(SEARCH_PARAMS.q) ?? '').trim(), sort: isAlbumSort(sort) ? sort : DEFAULT_SORT, - genres: parseValues(params, SEARCH_PARAMS.genres), + genres: parseValues(params, SEARCH_PARAMS.genres).filter(isGenreId), decades, }; } @@ -91,11 +105,15 @@ export function serializeSearchState(state: SearchState, currentSearch: string): params.delete(SEARCH_PARAMS.genres); params.delete(SEARCH_PARAMS.decades); - if (state.q) params.set(SEARCH_PARAMS.q, state.q); + const q = state.q.trim(); + if (q) params.set(SEARCH_PARAMS.q, q); if (state.sort !== DEFAULT_SORT) params.set(SEARCH_PARAMS.sort, state.sort); // One param per value rather than a comma joined list. URLSearchParams // percent encodes a comma into `%2C`, which makes a shared link unreadable. - for (const genre of state.genres) params.append(SEARCH_PARAMS.genres, genre); + // Genre ids are filtered here too, so the URL can never carry one the server + // would reject however the state was built. + for (const genre of state.genres.filter(isGenreId)) + params.append(SEARCH_PARAMS.genres, genre); for (const decade of state.decades) params.append(SEARCH_PARAMS.decades, String(decade));