From e8eef3797489f0f8dfd79b57fc63aa1c2f586c75 Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Sat, 24 Oct 2026 11:53:23 +0200 Subject: [PATCH 1/4] feat: #14 add infinite scroll and load more --- README.md | 5 +- client/src/App.test.tsx | 2 +- client/src/App.tsx | 24 +- client/src/components/ResultsLayout.css | 6 + client/src/components/ResultsLayout.tsx | 87 +++++- client/src/hooks/useAlbumSearch.ts | 145 ++++++++- client/src/pagination.test.tsx | 392 ++++++++++++++++++++++++ docs/AI-USAGE.md | 1 + 8 files changed, 632 insertions(+), 30 deletions(-) create mode 100644 client/src/pagination.test.tsx diff --git a/README.md b/README.md index a19e1e5..d89cc13 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ We consider sustainability through design choices that reduce unnecessary data t | `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | | Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | | `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | +| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages | | Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | | Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | | Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | @@ -196,9 +197,9 @@ The two `AlbumDetailPage` rows are the chunk added by the album detail route (#1 **Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`. `AVERAGE_RATING_DESC` is defined in the schema but currently returns an error because reviews are not implemented yet. -The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. It currently shows the first 20 matches ordered by relevance. +The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. -**Planned:** Frontend filters, sorting and pagination controls; album details; reviews, ratings and wantlist functionality; and Playwright end-to-end tests (M4). The database tables for reviews and crate items exist, but their GraphQL functionality is still planned. `X-User-Id` is also defined but not yet handled at runtime. Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. +**Planned:** Frontend filters and sorting controls; album details; reviews, ratings and wantlist functionality; and Playwright end-to-end tests (M4). The database tables for reviews and crate items exist, but their GraphQL functionality is still planned. `X-User-Id` is also defined but not yet handled at runtime. Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. ### Backend search behavior diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index ec47df6..945a25b 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -148,7 +148,7 @@ describe('App search', () => { expect(result).toHaveBeenCalledTimes(1); }); - it('starts with labelled search and accessible landmarks, without unrelated controls', () => { + it('starts with labelled search and accessible landmarks, hiding pagination until results exist', () => { renderApp(); expect( screen.getByRole('searchbox', { name: 'Search by album or artist' }), diff --git a/client/src/App.tsx b/client/src/App.tsx index 604b836..cebbc74 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -61,15 +61,21 @@ function DiscoveryPage() {
search.search('')} - /> + albums={search.albums} + totalCount={search.totalCount} + hasQuery={search.hasQuery} + loading={search.loading} + loadingMore={search.loadingMore} + pageError={search.pageError} + hasNextPage={search.hasNextPage} + onLoadMore={search.loadMore} + canLoadAutomatically={search.canLoadAutomatically} + onLoadMoreAutomatically={search.loadMoreAutomatically} + retrying={search.retrying} + error={search.error} + onRetry={search.retry} + onReset={() => search.search('')} + />
); diff --git a/client/src/components/ResultsLayout.css b/client/src/components/ResultsLayout.css index 653b2fb..0b85f27 100644 --- a/client/src/components/ResultsLayout.css +++ b/client/src/components/ResultsLayout.css @@ -1,6 +1,12 @@ .results { padding-bottom: 2.5rem; } + +.pagination { + text-align: center; + margin-top: 1.5rem; +} + .album-grid { list-style: none; margin: 0; diff --git a/client/src/components/ResultsLayout.tsx b/client/src/components/ResultsLayout.tsx index 8b9c0e8..4b13cfe 100644 --- a/client/src/components/ResultsLayout.tsx +++ b/client/src/components/ResultsLayout.tsx @@ -1,5 +1,6 @@ import './ResultsLayout.css'; +import { useEffect, useRef } from 'react'; import AlbumCard from './AlbumCard.js'; import type { AlbumSummary } from '../api/searchAlbums.js'; @@ -8,6 +9,12 @@ interface Props { totalCount: number; hasQuery: boolean; loading: boolean; + loadingMore: boolean; + pageError: boolean; + hasNextPage: boolean; + onLoadMore: () => void; + canLoadAutomatically: boolean; + onLoadMoreAutomatically: () => void; retrying: boolean; error: boolean; onRetry: () => void; @@ -15,11 +22,63 @@ interface Props { } export default function ResultsLayout(props: Props) { + const sentinel = useRef(null); + const { + hasNextPage, + loading, + loadingMore, + pageError, + canLoadAutomatically, + onLoadMoreAutomatically, + } = props; + + useEffect(() => { + if ( + !hasNextPage || + !canLoadAutomatically || + loading || + loadingMore || + pageError || + !sentinel.current || + typeof IntersectionObserver === 'undefined' + ) { + return; + } + + let active = true; + const observer = new IntersectionObserver( + (entries) => { + // Focus can scroll the button into view; let the user activate it. + if ( + active && + !sentinel.current?.contains(document.activeElement) && + entries.some((entry) => entry.isIntersecting) + ) { + onLoadMoreAutomatically(); + } + }, + { rootMargin: '300px' }, + ); + + observer.observe(sentinel.current); + return () => { + active = false; + observer.disconnect(); + }; + }, [ + hasNextPage, + loading, + loadingMore, + pageError, + canLoadAutomatically, + onLoadMoreAutomatically, + ]); + return (

Search results

@@ -31,7 +90,9 @@ export default function ResultsLayout(props: Props) { : 'Searching albums…' : props.error ? 'Search failed.' - : `Showing ${props.albums.length} of ${props.totalCount} albums.`} + : props.loadingMore + ? 'Loading more albums…' + : `Showing ${props.albums.length} of ${props.totalCount} albums.`}

{props.hasQuery && (props.error || props.retrying ? ( @@ -44,7 +105,9 @@ export default function ResultsLayout(props: Props) { className="primary-button" aria-disabled={props.loading} onClick={() => { - if (!props.loading) props.onRetry(); + if (!props.loading) { + props.onRetry(); + } }} > Retry search @@ -67,6 +130,24 @@ export default function ResultsLayout(props: Props) { ))} ))} + {props.hasQuery && !props.loading && !props.error && props.hasNextPage && ( +
+ {props.pageError && ( +

Could not load more albums. Please try again.

+ )} + +
+ )}
); } diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index 22d248d..e1e0a7c 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef } from 'react'; +import { useCallback, useMemo, useRef, useState } from 'react'; import { skipToken, useQuery } from '@apollo/client/react'; import { NetworkStatus } from '@apollo/client'; @@ -6,17 +6,16 @@ import { SEARCH_ALBUMS, type AlbumSearchInput } from '../api/searchAlbums.js'; import { useSearchState } from './useSearchState.js'; const PAGE_SIZE = 20; +const AUTOMATIC_PAGE_LIMIT = 2; export function useAlbumSearch() { const { state, setQuery } = useSearchState(); const query = state.q; const hasQuery = query.length > 0; const retryInFlight = useRef(false); + const pagesInFlight = useRef(new Set()); - // 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. + // The URL defines the result set; Apollo keeps its cached pages. const input = useMemo( () => ({ query, @@ -27,22 +26,127 @@ export function useAlbumSearch() { [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( + const { data, loading, error, refetch, fetchMore, networkStatus } = useQuery( SEARCH_ALBUMS, hasQuery ? { variables: { input, first: PAGE_SIZE, after: null }, - // Named rather than inherited. cache-first is Apollo's default, but - // spelling it out keeps the promise a repeated search costs no request - // at all, which is one of the bærekraft measures listed in the README. fetchPolicy: 'cache-first', } : skipToken, ); + const key = JSON.stringify(input); + const [pagination, setPagination] = useState({ + key, + visibleCount: PAGE_SIZE, + automaticPages: 0, + loadingMore: false, + pageError: false, + }); + + // Reset before committing results; the matching key prevents a render loop. + if (pagination.key !== key) { + setPagination({ + key, + visibleCount: PAGE_SIZE, + automaticPages: 0, + loadingMore: false, + pageError: false, + }); + } + + const canLoadAutomatically = + pagination.visibleCount < PAGE_SIZE * (AUTOMATIC_PAGE_LIMIT + 1) && + pagination.automaticPages < AUTOMATIC_PAGE_LIMIT; + + const pageInfo = data?.searchAlbums.pageInfo; + const edges = data?.searchAlbums.edges ?? []; + const hasCachedPage = edges.length > pagination.visibleCount; + + const hasNextPage = + hasQuery && (hasCachedPage || Boolean(pageInfo?.hasNextPage && pageInfo.endCursor)); + + const loadPage = useCallback( + (automatic: boolean) => { + const after = pageInfo?.endCursor; + if ( + !hasNextPage || + loading || + pagesInFlight.current.has(key) || + (automatic && !canLoadAutomatically) + ) { + return; + } + + const nextPagination = { + ...pagination, + automaticPages: pagination.automaticPages + (automatic ? 1 : 0), + }; + if (hasCachedPage) { + // Ignore repeated notifications before React renders the revealed page. + setPagination((current) => + current === pagination + ? { ...nextPagination, visibleCount: pagination.visibleCount + PAGE_SIZE } + : current, + ); + return; + } + + if (!after) { + return; + } + + // Guard clicks and observer notifications before the next render. + pagesInFlight.current.add(key); + const pendingPage = { ...pagination, loadingMore: true, pageError: false }; + setPagination(pendingPage); + + void fetchMore({ variables: { input, first: PAGE_SIZE, after } }) + .then(() => { + // Late pages stay cached but must not expand a different search visit. + setPagination((current) => + current === pendingPage + ? { + ...current, + visibleCount: current.visibleCount + PAGE_SIZE, + automaticPages: nextPagination.automaticPages, + loadingMore: false, + } + : current, + ); + }) + .catch(() => { + setPagination((current) => + current === pendingPage + ? { ...current, pageError: true, loadingMore: false } + : current, + ); + }) + .finally(() => { + pagesInFlight.current.delete(key); + }); + }, + [ + hasNextPage, + loading, + key, + fetchMore, + input, + pageInfo, + canLoadAutomatically, + pagination, + hasCachedPage, + ], + ); + + const loadMore = useCallback(() => loadPage(false), [loadPage]); + const loadMoreAutomatically = useCallback(() => loadPage(true), [loadPage]); + const retry = useCallback(() => { - if (!hasQuery || !error || loading || retryInFlight.current) return; + if (!hasQuery || !error || loading || retryInFlight.current) { + return; + } // Guard rapid clicks before Apollo publishes the next loading render. retryInFlight.current = true; @@ -59,8 +163,11 @@ export function useAlbumSearch() { (text: string) => { const nextQuery = text.trim(); - if (nextQuery !== query) setQuery(nextQuery); - else retry(); + if (nextQuery !== query) { + setQuery(nextQuery); + } else { + retry(); + } }, [query, setQuery, retry], ); @@ -69,9 +176,17 @@ export function useAlbumSearch() { query, search, hasQuery, - albums: hasQuery ? (data?.searchAlbums.edges.map((edge) => edge.node) ?? []) : [], + albums: hasQuery + ? edges.slice(0, pagination.visibleCount).map((edge) => edge.node) + : [], totalCount: hasQuery ? (data?.searchAlbums.totalCount ?? 0) : 0, - loading: hasQuery && loading, + loading: hasQuery && loading && networkStatus !== NetworkStatus.fetchMore, + loadingMore: pagination.loadingMore, + pageError: pagination.pageError, + hasNextPage, + loadMore, + canLoadAutomatically, + loadMoreAutomatically, // Refetch status distinguishes retries even when Apollo clears the previous error. retrying: hasQuery && networkStatus === NetworkStatus.refetch, error: hasQuery && Boolean(error), diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx new file mode 100644 index 0000000..ccfc8f8 --- /dev/null +++ b/client/src/pagination.test.tsx @@ -0,0 +1,392 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + act, + fireEvent, + render, + renderHook, + 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'; +import App from './App.js'; +import { cache } from './api/client.js'; +import { useAlbumSearch } from './hooks/useAlbumSearch.js'; +import { + SEARCH_ALBUMS, + type AlbumSearchInput, + type SearchAlbumsData, + type SearchAlbumsVariables, +} from './api/searchAlbums.js'; + +const input: AlbumSearchInput = { query: 'record', sort: 'RELEVANCE' }; +const searchChanges: [string, AlbumSearchInput][] = [ + ['?q=other', { ...input, query: 'other' }], + ['?q=record&sort=TITLE_ASC', { ...input, sort: 'TITLE_ASC' }], + ['?q=record&genres=1', { ...input, genreIds: ['1'] }], + ['?q=record&decades=1990', { ...input, decades: [1990] }], +]; + +function page( + id: string, + after: string | null = null, + hasNextPage = false, + searchInput = input, + ids = [id], +) { + return { + request: { + query: SEARCH_ALBUMS, + variables: { input: searchInput, first: 20, after }, + }, + result: { + data: { + searchAlbums: { + edges: ids.map((albumId) => ({ + cursor: albumId, + node: { + id: albumId, + title: `Album ${albumId}`, + artists: [], + genres: [], + releaseYear: null, + averageRating: null, + reviewCount: 0, + }, + })), + totalCount: 40, + pageInfo: { endCursor: id, hasNextPage }, + }, + }, + }, + delay: 10, + } satisfies MockLink.MockedResponse; +} + +function start( + mocks: MockLink.MockedResponse[], +) { + window.history.replaceState({}, '', '/?q=record'); + // Reuse the production policies, clearing cached results for each test. + render( + + + , + ); +} + +function navigate(query: string) { + act(() => { + window.history.pushState({}, '', query); + window.dispatchEvent(new PopStateEvent('popstate')); + }); +} +afterEach(() => vi.unstubAllGlobals()); + +function observeEnd() { + let notify: IntersectionObserverCallback = () => {}; + const disconnect = vi.fn(); + vi.stubGlobal( + 'IntersectionObserver', + class { + constructor(callback: IntersectionObserverCallback) { + notify = callback; + } + observe = vi.fn(); + disconnect = disconnect; + }, + ); + const intersect = () => + act(() => + notify( + [{ isIntersecting: true }] as IntersectionObserverEntry[], + {} as IntersectionObserver, + ), + ); + + return { intersect, disconnect }; +} + +function fullPage(last: number, searchInput = input) { + const mock = page( + String(last), + last === 20 ? null : String(last - 20), + true, + searchInput, + Array.from({ length: 20 }, (_, index) => String(last - 19 + index)), + ); + mock.result.data.searchAlbums.totalCount = 100; + + return mock; +} + +describe('cursor pagination', () => { + it.each(searchChanges)( + 'returns from %s to 20 visible albums, reveals cached pages, then fetches page 5', + async (url, changed) => { + const { intersect } = observeEnd(); + const requests = [20, 40, 60, 80, 100].map((last) => { + const mock = fullPage(last); + const response = mock.result; + if (last === 100) { + response.data.searchAlbums.pageInfo.hasNextPage = false; + } + return { ...mock, result: vi.fn(() => response), maxUsageCount: 3 }; + }); + start([...requests, page('other', null, false, changed)]); + await screen.findByRole('article', { name: 'Album 20' }); + for (const last of [40, 60, 80]) { + fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + await screen.findByRole('article', { name: `Album ${last}` }); + } + navigate(url); + await screen.findByRole('article', { name: 'Album other' }); + navigate('?q=record'); + expect(screen.getByRole('status')).toHaveTextContent('Showing 20 of 100 albums.'); + expect(screen.getAllByRole('article')).toHaveLength(20); + for (const count of [40, 60]) { + intersect(); + expect(screen.getByRole('status')).toHaveTextContent( + `Showing ${count} of 100 albums.`, + ); + } + intersect(); + expect(screen.getAllByRole('article')).toHaveLength(60); + const button = screen.getByRole('button', { name: 'Load more' }); + // Repeated clicks in one render reveal just one cached batch. + act(() => { + fireEvent.click(button); + fireEvent.click(button); + }); + expect(screen.getByRole('status')).toHaveTextContent('Showing 80 of 100 albums.'); + for (const request of requests.slice(0, 4)) { + expect(request.result).toHaveBeenCalledTimes(1); + } + expect(requests[4]!.result).not.toHaveBeenCalled(); + fireEvent.click(button); + await screen.findByRole('article', { name: 'Album 100' }); + expect(requests[4]!.result).toHaveBeenCalledTimes(1); + expect(screen.getAllByRole('article')).toHaveLength(100); + expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); + // A fully cached terminal connection still has hidden pages on return. + navigate(url); + navigate('?q=record'); + expect(screen.getAllByRole('article')).toHaveLength(20); + expect(screen.getByRole('button', { name: 'Load more' })).toBeInTheDocument(); + }, + 15000, + ); + + it('does not reveal a late page when returning to the same search visit', async () => { + start([ + fullPage(20), + { ...fullPage(40), delay: 150 }, + page('other', null, false, { ...input, query: 'other' }), + ]); + fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); + navigate('?q=other'); + await screen.findByRole('article', { name: 'Album other' }); + navigate('?q=record'); + await act(() => new Promise((resolve) => setTimeout(resolve, 200))); + expect(screen.getAllByRole('article')).toHaveLength(20); + fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + expect(screen.getAllByRole('article')).toHaveLength(40); + }); + + it('stops automatic loading at 60 albums and allows subsequent manual pages', async () => { + const { intersect } = observeEnd(); + start([20, 40, 60, 80, 100].map((last) => fullPage(last))); + await screen.findByRole('article', { name: 'Album 20' }); + intersect(); + intersect(); // Repeated notifications must not consume another allowance. + await screen.findByRole('article', { name: 'Album 40' }); + intersect(); + await screen.findByRole('article', { name: 'Album 60' }); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent('Showing 60 of 100 albums.'); + const button = screen.getByRole('button', { name: 'Load more' }); + expect(button).toHaveAttribute('aria-disabled', 'false'); + fireEvent.click(button); + await screen.findByRole('article', { name: 'Album 80' }); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent('Showing 80 of 100 albums.'); + fireEvent.click(button); + await screen.findByRole('article', { name: 'Album 100' }); + }); + + it.each(searchChanges)( + 'resets the two-page automatic allowance for %s', + async (url, changed) => { + const { intersect } = observeEnd(); + start([ + page('1', null, true), + page('2', '1', true), + page('3', '2', true), + page('4', null, true, changed), + page('5', '4', true, changed), + page('6', '5', true, changed), + ]); + await screen.findByRole('article', { name: 'Album 1' }); + intersect(); + await screen.findByRole('article', { name: 'Album 2' }); + intersect(); + await screen.findByRole('article', { name: 'Album 3' }); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent('Showing 3 of 40 albums.'); + navigate(url); + await screen.findByRole('article', { name: 'Album 4' }); + intersect(); + await screen.findByRole('article', { name: 'Album 5' }); + intersect(); + await screen.findByRole('article', { name: 'Album 6' }); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent('Showing 3 of 40 albums.'); + }, + ); + + it('loads manually with the keyboard, keeps results visible, and stops at the final page', async () => { + start([page('1', null, true), { ...page('2', '1'), delay: 100 }]); + const button = await screen.findByRole('button', { name: 'Load more' }); + button.focus(); + await userEvent.setup().keyboard('{Enter}'); + expect(screen.getByRole('article', { name: 'Album 1' })).toBeInTheDocument(); + expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); + expect(button).toHaveFocus(); + await screen.findByRole('article', { name: 'Album 2' }); + expect(screen.getAllByRole('article')).toHaveLength(2); + expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); + }); + + it.each(['{Enter}', ' '])( + 'keeps Load more available after Tab until activated with %s', + async (key) => { + const { intersect } = observeEnd(); + const next = page('2', '1', true); + const result = vi.fn(() => next.result); + start([page('1', null, true), { ...next, result, delay: 100 }]); + const button = await screen.findByRole('button', { name: 'Load more' }); + const user = userEvent.setup(); + screen.getByRole('button', { name: 'Search' }).focus(); + await user.tab(); + expect(button).toHaveFocus(); + + // Browsers scroll a newly focused button into view, notifying the observer. + intersect(); + expect(button).toHaveAttribute('aria-disabled', 'false'); + expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 40 albums.'); + expect(result).not.toHaveBeenCalled(); + + await user.keyboard(key); + expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); + await screen.findByRole('article', { name: 'Album 2' }); + expect(result).toHaveBeenCalledTimes(1); + expect(button).toHaveFocus(); + intersect(); + expect(button).toHaveAttribute('aria-disabled', 'false'); + expect(screen.getByRole('status')).toHaveTextContent('Showing 2 of 40 albums.'); + }, + ); + + it('automatically loads near the end and prevents overlapping observer and button requests', async () => { + const { intersect, disconnect } = observeEnd(); + const next = page('2', '1'); + const result = vi.fn(() => next.result); + start([page('1', null, true), { ...next, result, delay: 100, maxUsageCount: 3 }]); + const button = await screen.findByRole('button', { name: 'Load more' }); + act(() => { + intersect(); + intersect(); + fireEvent.click(button); + }); + await screen.findByRole('article', { name: 'Album 2' }); + expect(result).toHaveBeenCalledTimes(1); + expect(disconnect).toHaveBeenCalled(); + }); + + it('counts only successful automatic pages and keeps manual retry available', async () => { + window.history.replaceState({}, '', '/?q=record'); + const failedPage = { + ...fullPage(60), + result: undefined, + error: new Error('Offline'), + }; + const mocks = [fullPage(20), fullPage(40), failedPage, fullPage(60)]; + const { result } = renderHook(() => useAlbumSearch(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + await waitFor(() => expect(result.current.albums).toHaveLength(20)); + act(() => result.current.loadMoreAutomatically()); + await waitFor(() => expect(result.current.albums).toHaveLength(40)); + + act(() => result.current.loadMoreAutomatically()); + await waitFor(() => expect(result.current.pageError).toBe(true)); + expect(result.current.albums).toHaveLength(40); + expect(result.current.loadingMore).toBe(false); + expect(result.current.canLoadAutomatically).toBe(true); + + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.albums).toHaveLength(60)); + expect(result.current.pageError).toBe(false); + expect(result.current.canLoadAutomatically).toBe(false); + }); + + it('retains albums on page failure and retries the same cursor manually', async () => { + const failed = { ...page('2', '1'), result: undefined, error: new Error('Offline') }; + start([page('1', null, true), failed, page('2', '1')]); + fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not load more albums', + ); + expect(screen.getByRole('article', { name: 'Album 1' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + await screen.findByRole('article', { name: 'Album 2' }); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('starts a changed search from its first page and uses its new cursor', async () => { + const changed = { ...input, query: 'other' }; + start([ + page('1', null, true), + page('2', '1'), + page('3', null, true, changed), + page('4', '3', false, changed), + ]); + fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); + await screen.findByRole('article', { name: 'Album 2' }); + navigate('?q=other'); + fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); + await screen.findByRole('article', { name: 'Album 4' }); + expect(screen.getAllByRole('article')).toHaveLength(2); + expect(screen.getByRole('article', { name: 'Album 3' })).toBeInTheDocument(); + expect(screen.queryByRole('article', { name: 'Album 1' })).not.toBeInTheDocument(); + }); + + it.each(searchChanges)( + 'resets the cursor for %s and isolates late pages', + async (url, changed) => { + start([ + page('1', null, true), + { ...page('2', '1'), delay: 100 }, + page('3', null, true, changed), + ]); + fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); + navigate(url); + await screen.findByRole('article', { name: 'Album 3' }); + await act(() => new Promise((resolve) => setTimeout(resolve, 150))); + expect(screen.getAllByRole('article')).toHaveLength(1); + expect(screen.queryByRole('article', { name: 'Album 2' })).not.toBeInTheDocument(); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Load more' })).toHaveAttribute( + 'aria-disabled', + 'false', + ), + ); + }, + ); +}); diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index c3b744c..673d560 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -65,6 +65,7 @@ the part that matters most. | 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. | | 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. | | 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing prefix search (#55), performance testing with 100,000 albums, and updating documentation. | +| 2026-10-24 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing cursor pagination, infinite scroll, Load more, Apollo cache handling, and accessibility improvements (#14). | ## Notes From cb0b4d241793f6cec623211ebbe8ad7f8f012fa9 Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Sat, 24 Oct 2026 14:42:50 +0200 Subject: [PATCH 2/4] docs: #14 update sustainability measurements --- README.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d89cc13..a577055 100644 --- a/README.md +++ b/README.md @@ -161,21 +161,19 @@ We consider sustainability through design choices that reduce unnecessary data t | Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | | Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | -**Bundle size**, production build measured 21 October 2026: +**Bundle size**, production build measured 24 October 2026: | File | Raw | Gzip | | ----------------------- | --------: | --------: | -| `index-*.js` | 425.02 kB | 129.12 kB | -| `index-*.css` | 4.85 kB | 1.73 kB | +| `index-*.js` | 427.22 kB | 129.78 kB | +| `index-*.css` | 4.90 kB | 1.75 kB | | `AlbumDetailPage-*.js` | 3.73 kB | 1.30 kB | | `AlbumDetailPage-*.css` | 1.26 kB | 0.53 kB | -| `index.html` | 0.51 kB | 0.31 kB | +| `index.html` | 0.51 kB | 0.32 kB | -The two `AlbumDetailPage` rows are the chunk added by the album detail route (#11) and are not part of the search page payload. Note that the album link is a full page load today, so opening an album re-downloads the main bundle as well; the split still keeps the detail page out of the initial payload. +The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. The album link currently causes a full page load, so opening an album also reloads the main bundle. -**Requests for a typical search: one.** The client has exactly one `useQuery`, so a search is a single `searchAlbums` request. Nothing is sent while the page is idle and nothing while the user types. Searching again for something already in the cache sends nothing. Opening an album is one further `album(id:)` request. - -**Accessibility and bærekraft pull in the same direction here.** No request until Search is pressed is also why the result count is announced once instead of on every keystroke, and `prefers-reduced-motion` costs nothing for anyone who does not ask for it. +**Requests for a typical search:** An uncached search initially fetches up to 20 albums in one `searchAlbums` request. Infinite scroll loads up to two additional pages automatically, while further pages are loaded using the Load more button. Previously fetched pages are reused from Apollo's cache without new requests. No search requests are sent while the user types. ## Project status From f77f8403268685a698c73fa0a84a17342a01797d Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Mon, 26 Oct 2026 11:36:35 +0100 Subject: [PATCH 3/4] test: #14 update tests after merging main --- README.md | 12 ++++++------ client/src/App.test.tsx | 11 +++++++++-- client/src/pagination.test.tsx | 26 +++++++++++++++----------- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index a577055..bf70c8b 100644 --- a/README.md +++ b/README.md @@ -161,15 +161,15 @@ We consider sustainability through design choices that reduce unnecessary data t | Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | | Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | -**Bundle size**, production build measured 24 October 2026: +**Bundle size**, production build measured 26 October 2026: | File | Raw | Gzip | | ----------------------- | --------: | --------: | -| `index-*.js` | 427.22 kB | 129.78 kB | -| `index-*.css` | 4.90 kB | 1.75 kB | -| `AlbumDetailPage-*.js` | 3.73 kB | 1.30 kB | -| `AlbumDetailPage-*.css` | 1.26 kB | 0.53 kB | -| `index.html` | 0.51 kB | 0.32 kB | +| `index-*.js` | 430.26 kB | 131.10 kB | +| `index-*.css` | 4.99 kB | 1.77 kB | +| `AlbumDetailPage-*.js` | 8.29 kB | 2.88 kB | +| `AlbumDetailPage-*.css` | 1.94 kB | 0.71 kB | +| `index.html` | 0.51 kB | 0.31 kB | The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. The album link currently causes a full page load, so opening an album also reloads the main bundle. diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 945a25b..bbe6081 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -179,9 +179,16 @@ describe('App search', () => { expect(window.location.search).toBe('?q=Abbey'); }); - it('returns to an empty discovery page from the main navigation', () => { + it('returns to an empty discovery page from the main navigation', async () => { window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); - renderApp(); + const mock = mockSearch('Abbey'); + mock.request.variables = { + input: { query: 'Abbey', sort: 'TITLE_ASC' }, + first: 20, + after: null, + }; + renderApp([mock]); + await screen.findByRole('article', { name: 'Abbey Road' }); expect(screen.getByRole('link', { name: 'Discover' })).toHaveAttribute( 'href', diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index ccfc8f8..2b07c4c 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -76,8 +76,8 @@ function start( ); } -function navigate(query: string) { - act(() => { +async function navigate(query: string) { + await act(async () => { window.history.pushState({}, '', query); window.dispatchEvent(new PopStateEvent('popstate')); }); @@ -140,9 +140,9 @@ describe('cursor pagination', () => { fireEvent.click(screen.getByRole('button', { name: 'Load more' })); await screen.findByRole('article', { name: `Album ${last}` }); } - navigate(url); + await navigate(url); await screen.findByRole('article', { name: 'Album other' }); - navigate('?q=record'); + await navigate('?q=record'); expect(screen.getByRole('status')).toHaveTextContent('Showing 20 of 100 albums.'); expect(screen.getAllByRole('article')).toHaveLength(20); for (const count of [40, 60]) { @@ -170,8 +170,8 @@ describe('cursor pagination', () => { expect(screen.getAllByRole('article')).toHaveLength(100); expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); // A fully cached terminal connection still has hidden pages on return. - navigate(url); - navigate('?q=record'); + await navigate(url); + await navigate('?q=record'); expect(screen.getAllByRole('article')).toHaveLength(20); expect(screen.getByRole('button', { name: 'Load more' })).toBeInTheDocument(); }, @@ -185,9 +185,9 @@ describe('cursor pagination', () => { page('other', null, false, { ...input, query: 'other' }), ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); - navigate('?q=other'); + await navigate('?q=other'); await screen.findByRole('article', { name: 'Album other' }); - navigate('?q=record'); + await navigate('?q=record'); await act(() => new Promise((resolve) => setTimeout(resolve, 200))); expect(screen.getAllByRole('article')).toHaveLength(20); fireEvent.click(screen.getByRole('button', { name: 'Load more' })); @@ -234,7 +234,7 @@ describe('cursor pagination', () => { await screen.findByRole('article', { name: 'Album 3' }); intersect(); expect(screen.getByRole('status')).toHaveTextContent('Showing 3 of 40 albums.'); - navigate(url); + await navigate(url); await screen.findByRole('article', { name: 'Album 4' }); intersect(); await screen.findByRole('article', { name: 'Album 5' }); @@ -268,6 +268,10 @@ describe('cursor pagination', () => { const button = await screen.findByRole('button', { name: 'Load more' }); const user = userEvent.setup(); screen.getByRole('button', { name: 'Search' }).focus(); + + await user.tab(); + expect(screen.getByRole('link', { name: 'Album 1' })).toHaveFocus(); + await user.tab(); expect(button).toHaveFocus(); @@ -359,7 +363,7 @@ describe('cursor pagination', () => { ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); await screen.findByRole('article', { name: 'Album 2' }); - navigate('?q=other'); + await navigate('?q=other'); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); await screen.findByRole('article', { name: 'Album 4' }); expect(screen.getAllByRole('article')).toHaveLength(2); @@ -376,7 +380,7 @@ describe('cursor pagination', () => { page('3', null, true, changed), ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); - navigate(url); + await navigate(url); await screen.findByRole('article', { name: 'Album 3' }); await act(() => new Promise((resolve) => setTimeout(resolve, 150))); expect(screen.getAllByRole('article')).toHaveLength(1); From dccd6b7862c71ba59ce00dc148fecffce9ff20ff Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Mon, 26 Oct 2026 15:14:40 +0100 Subject: [PATCH 4/4] docs: #14 update AI log and formatting after rebase --- README.md | 22 +++++++++++----------- client/src/App.tsx | 30 +++++++++++++++--------------- docs/AI-USAGE.md | 4 +++- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index bf70c8b..cebc2f1 100644 --- a/README.md +++ b/README.md @@ -149,17 +149,17 @@ The read-only benchmark is available in `server/scripts/prefix-search-perf.sql`. We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs. -| Measure | Resource consideration | Effect | -| ------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | -| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | -| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | -| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | -| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | -| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages | -| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | -| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | -| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | +| Measure | Resource consideration | Effect | +| ---------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | +| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | +| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | +| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | +| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | +| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages | +| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | +| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | +| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | **Bundle size**, production build measured 26 October 2026: diff --git a/client/src/App.tsx b/client/src/App.tsx index cebbc74..fde583b 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -61,21 +61,21 @@ function DiscoveryPage() {
search.search('')} - /> + albums={search.albums} + totalCount={search.totalCount} + hasQuery={search.hasQuery} + loading={search.loading} + loadingMore={search.loadingMore} + pageError={search.pageError} + hasNextPage={search.hasNextPage} + onLoadMore={search.loadMore} + canLoadAutomatically={search.canLoadAutomatically} + onLoadMoreAutomatically={search.loadMoreAutomatically} + retrying={search.retrying} + error={search.error} + onRetry={search.retry} + onReset={() => search.search('')} + />
); diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 673d560..5fbcd3c 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -64,8 +64,10 @@ the part that matters most. | 2026-10-22 | erikhfj | opencode | Reviewed #57 and #58 by running the full gate suite on the branches rather than reading them as prose. Six findings on each. One of mine was wrong: I wrote that `App.tsx` was the only file in the repo carrying a UTF-8 BOM. It is one of four, and three predate that PR entirely. Posted a correction rather than leaving the error standing. Recorded here because a wrong review is as much a failure of control as a wrong patch. | | 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. | | 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. | +| 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with reviewing PRs #59, #60, #57 and #58, examining and explaining code changes, identifying potential issues and evaluating test coverage. | | | 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing prefix search (#55), performance testing with 100,000 albums, and updating documentation. | -| 2026-10-24 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing cursor pagination, infinite scroll, Load more, Apollo cache handling, and accessibility improvements (#14). | +| 2026-10-24 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing cursor pagination, infinite scroll, Load more, Apollo cache handling, and accessibility improvements (#14). | +| 2026-10-25 | rachelks | ChatGPT | Assisted with researching real album datasets, evaluating which data source best fit the project, and planning issues #63 and #64 to implement real data. | ## Notes