diff --git a/client/src/App.css b/client/src/App.css index 9e6ae12..e29f8b7 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -5,6 +5,9 @@ min-block-size: 100svh; padding-block: 2rem 3rem; } +.route-error { + padding-block: 3rem; +} .skip-link { position: absolute; left: -9999px; diff --git a/client/src/App.tsx b/client/src/App.tsx index 7c8ccbd..4e76f6c 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,22 +1,71 @@ import './App.css'; -import SearchForm from './components/SearchForm.js'; -import ResultsLayout from './components/ResultsLayout.js'; -import { lazy, Suspense } from 'react'; +import { lazy, Suspense, useCallback, useEffect, useRef } from 'react'; -import { useAlbumSearch } from './hooks/useAlbumSearch.js'; -import { useSearchHistory } from './hooks/useSearchHistory.js'; +import Link from './components/Link.js'; +import RouteErrorBoundary from './components/RouteErrorBoundary.js'; +import DiscoveryPage from './pages/DiscoveryPage.js'; +import { appHref, stripBasePath, useLocation } from './router.js'; + +function focusMain(): void { + const main = document.getElementById('main'); + if (main instanceof HTMLElement) { + main.focus({ preventScroll: true }); + } +} + +/** + * Fires after a lazy route inside `` finishes mounting so focus + * moves from the unmounted fallback `
` to the real page `
`. + */ +function RouteFocusSettler({ + pathname, + onSettled, +}: { + pathname: string; + onSettled: (pathname: string) => void; +}) { + useEffect(() => { + onSettled(pathname); + }, [pathname, onSettled]); + return null; +} export default function App() { - const basePath = import.meta.env.BASE_URL.replace(/\/$/, ''); - const discoveryHref = import.meta.env.BASE_URL; - const pathname = window.location.pathname.startsWith(basePath) - ? window.location.pathname.slice(basePath.length) || '/' - : window.location.pathname; + const location = useLocation(); + const discoveryHref = appHref('/'); + const crateHref = appHref('/crate'); + const pathname = stripBasePath(location.pathname); const detailMatch = /^\/album\/(\d+)$/.exec(pathname); const detailId = detailMatch?.[1]; const isCrate = pathname === '/crate'; + const previousPathname = useRef(pathname); + const pendingFocusPathname = useRef(null); + + useEffect(() => { + if (previousPathname.current === pathname) return; + previousPathname.current = pathname; + focusMain(); + const main = document.getElementById('main'); + pendingFocusPathname.current = main?.hasAttribute('data-route-fallback') + ? pathname + : null; + }, [pathname]); + + const handleRouteSettled = useCallback((settledPathname: string) => { + if (pendingFocusPathname.current !== settledPathname) return; + pendingFocusPathname.current = null; + // Only move focus if it fell back to when the Suspense fallback unmounted. + if ( + !document.activeElement || + document.activeElement === document.body || + document.activeElement === document.documentElement + ) { + focusMain(); + } + }, []); + return ( <> @@ -24,118 +73,57 @@ export default function App() {
- {detailId ? ( - -

Loading album…

-
- } - > - - - ) : isCrate ? ( - -

Loading your crate…

-
- } - > - -
- ) : ( - - )} + + {detailId ? ( + +

Loading album…

+ + } + > + + +
+ ) : isCrate ? ( + +

Loading your crate…

+ + } + > + + +
+ ) : ( + + )} +
); } -function DiscoveryPage() { - const search = useAlbumSearch(); - const history = useSearchHistory(); - - function submitSearch(query: string) { - search.search(query); - history.recordSearch(query); - } - - return ( -
-
-
-

Your next favorite is in here

-

- Music worth -
holding onto. -

-

- Search, rate and collect albums you’ll want to return to. -

- -

- Photo by{' '} - - Kevin McCutcheon on Unsplash - -

-
-
-
- -
-
- ); -} - const AlbumDetailPage = lazy(() => import('./pages/AlbumDetailPage.js')); const CratePage = lazy(() => import('./pages/CratePage.js')); diff --git a/client/src/api/client.test.ts b/client/src/api/client.test.ts index 563347c..40621ec 100644 --- a/client/src/api/client.test.ts +++ b/client/src/api/client.test.ts @@ -3,6 +3,12 @@ import { buildSchema, print, validate, type FieldNode } from 'graphql'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { cache } from './client.js'; +import { MY_CRATE } from './crate.js'; +import { + DELETE_REVIEW, + UPSERT_REVIEW, + updateCacheAfterReviewMutation, +} from './reviews.js'; import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from './searchAlbums.js'; import { MY_SEARCH_HISTORY } from './searchHistory.js'; import type { @@ -196,3 +202,138 @@ describe('searchAlbums cache policy', () => { expect(read()?.searchAlbums.pageInfo.endCursor).toBe('cursor-2'); }); }); + +describe('myCrate cache policy and review mutation cache updates', () => { + function crateResult(ids: string[], endCursor: string | null, hasNextPage = true) { + return { + myCrate: { + edges: ids.map((id) => ({ + cursor: `crate-${id}`, + node: { + __typename: 'CrateItem' as const, + id: `item-${id}`, + addedAt: '2026-11-20T12:00:00.000Z', + album: { + __typename: 'Album' as const, + id, + title: `Album ${id}`, + releaseYear: 1990, + musicBrainzReleaseGroupId: null, + averageRating: null, + reviewCount: 0, + isInCrate: true, + artists: [], + genres: [], + }, + }, + })), + pageInfo: { hasNextPage, endCursor }, + totalCount: 3, + }, + }; + } + + it('merges myCrate pages using the shared cursor connection policy', () => { + cache.writeQuery({ + query: MY_CRATE, + variables: { first: 2, after: null }, + data: crateResult(['1', '2'], 'crate-2', true), + }); + cache.writeQuery({ + query: MY_CRATE, + variables: { first: 2, after: 'crate-2' }, + data: crateResult(['2', '3'], 'crate-3', false), + }); + + const crate = cache.readQuery({ + query: MY_CRATE, + variables: { first: 2, after: null }, + })?.myCrate; + + expect(crate?.edges.map((edge) => edge.node.album.id)).toEqual(['1', '2', '3']); + expect(crate?.pageInfo).toEqual({ hasNextPage: false, endCursor: 'crate-3' }); + }); + + it('relies on Apollo normalization for myCrate stats and evicts stale searchAlbums after review mutations', () => { + write(result(['1', '2'], 'cursor-2')); + cache.writeQuery({ + query: MY_CRATE, + variables: { first: 20, after: null }, + data: crateResult(['1'], 'crate-1', false), + }); + + const upsertResult = { + upsertReview: { + __typename: 'ReviewMutationPayload' as const, + review: { + __typename: 'Review' as const, + id: 'r1', + rating: 5, + comment: 'Great record', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + album: { + __typename: 'Album' as const, + id: '1', + averageRating: 4.5, + reviewCount: 2, + myReview: { + __typename: 'Review' as const, + id: 'r1', + rating: 5, + comment: 'Great record', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + }, + }, + }; + cache.write({ + query: UPSERT_REVIEW, + variables: { input: { albumId: '1', rating: 5, comment: 'Great record' } }, + dataId: 'ROOT_MUTATION', + result: upsertResult, + }); + updateCacheAfterReviewMutation(cache); + + const crateAfterUpsert = cache.readQuery({ + query: MY_CRATE, + variables: { first: 20, after: null }, + })?.myCrate; + expect(crateAfterUpsert?.edges[0]?.node.album.averageRating).toBe(4.5); + expect(crateAfterUpsert?.edges[0]?.node.album.reviewCount).toBe(2); + expect(read()).toBeNull(); + + // Deleting the last review normalizes album stats back to null/0 and evicts searchAlbums. + write(result(['1', '2'], 'cursor-2')); + const deleteResult = { + deleteReview: { + __typename: 'DeleteReviewPayload' as const, + deletedReviewId: 'r1', + album: { + __typename: 'Album' as const, + id: '1', + averageRating: null, + reviewCount: 0, + myReview: null, + }, + }, + }; + cache.write({ + query: DELETE_REVIEW, + variables: { id: 'r1' }, + dataId: 'ROOT_MUTATION', + result: deleteResult, + }); + updateCacheAfterReviewMutation(cache); + + const crateAfterDelete = cache.readQuery({ + query: MY_CRATE, + variables: { first: 20, after: null }, + })?.myCrate; + expect(crateAfterDelete?.edges[0]?.node.album.averageRating).toBeNull(); + expect(crateAfterDelete?.edges[0]?.node.album.reviewCount).toBe(0); + expect(read()).toBeNull(); + }); +}); diff --git a/client/src/api/client.ts b/client/src/api/client.ts index 12c72ed..81c9368 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -1,25 +1,65 @@ import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'; -import type { Reference, StoreObject } from '@apollo/client'; +import type { FieldFunctionOptions, Reference, StoreObject } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; import type { AlbumConnection } from './searchAlbums.js'; import { getUserId } from './userIdentity.js'; +type CachedEdge = { cursor: string; node: Reference | StoreObject }; + +type CursorConnection = { + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + edges: CachedEdge[]; +}; + // Album nodes are normalized references inside the cache, not query-result objects. // A Load more page (SEARCH_ALBUMS_PAGE) carries only edges and pageInfo. type CachedConnection = Partial> & Pick & { - edges: { cursor: string; node: Reference | StoreObject }[]; + edges: CachedEdge[]; }; // The crate is one list per user, so no arguments belong in its cache key; only // the paging argument decides whether this is another page or a refresh. -type CachedCrate = { - pageInfo: { hasNextPage: boolean; endCursor: string | null }; - edges: { cursor: string; node: Reference | StoreObject }[]; +type CachedCrate = CursorConnection & { totalCount: number; }; +/** + * Shared keyset-cursor pagination merger for normalized GraphQL connections. + * Replaces on first-page refreshes, ignores stale/repeated continuations, + * deduplicates appended edges by node ID, and preserves first-page fields + * omitted by lighter continuation queries. + */ +function mergeCursorConnection( + existing: T | undefined, + incoming: T, + { args, readField }: FieldFunctionOptions, +): T { + // A first-page refresh must replace any previously accumulated pages. + if (!args?.after) return incoming; + + // Only append to the current tail. Ignore repeated or stale continuations. + if (!existing || args.after !== existing.pageInfo.endCursor) { + return existing ?? incoming; + } + + const ids = new Set(existing.edges.map((edge) => readField('id', edge.node))); + const edges = [...existing.edges]; + + for (const edge of incoming.edges) { + const id = readField('id', edge.node); + + if (!ids.has(id)) { + ids.add(id); + edges.push(edge); + } + } + + // Later pages may leave out first-page aggregates (counts/facets), so existing stays. + return { ...existing, ...incoming, edges }; +} + // InMemoryCache stores server results and shares album records by their IDs. export const cache = new InMemoryCache({ typePolicies: { @@ -33,36 +73,12 @@ export const cache = new InMemoryCache({ searchAlbums: { // Each complete search input gets its own list; paging arguments do not. keyArgs: ['input'], - merge( existing: CachedConnection | undefined, incoming: CachedConnection, - { args, readField }, + options, ): CachedConnection { - // A first-page refresh must replace any previously accumulated pages. - if (!args?.after) return incoming; - - // Only append to the current tail. Ignore repeated or stale continuations. - if (!existing || args.after !== existing.pageInfo.endCursor) { - return existing ?? incoming; - } - - const ids = new Set( - existing.edges.map((edge) => readField('id', edge.node)), - ); - const edges = [...existing.edges]; - - for (const edge of incoming.edges) { - const id = readField('id', edge.node); - - if (!ids.has(id)) { - ids.add(id); - edges.push(edge); - } - } - - // Later pages leave out the count and facets, so the first page's stay. - return { ...existing, ...incoming, edges }; + return mergeCursorConnection(existing, incoming, options); }, }, @@ -70,32 +86,12 @@ export const cache = new InMemoryCache({ // One crate per user, so there is nothing to key on: `after` is paging, // not a different list. The user id never reaches the cache key. keyArgs: false, - merge( existing: CachedCrate | undefined, incoming: CachedCrate, - { args, readField }, + options, ): CachedCrate { - // A reload of the first page replaces whatever was accumulated. - if (!args?.after) return incoming; - if (!existing || args.after !== existing.pageInfo.endCursor) { - return existing ?? incoming; - } - - const ids = new Set( - existing.edges.map((edge) => readField('id', edge.node)), - ); - const edges = [...existing.edges]; - - for (const edge of incoming.edges) { - const id = readField('id', edge.node); - if (!ids.has(id)) { - ids.add(id); - edges.push(edge); - } - } - - return { ...incoming, edges }; + return mergeCursorConnection(existing, incoming, options); }, }, }, diff --git a/client/src/api/reviews.ts b/client/src/api/reviews.ts index 10a2f64..899a909 100644 --- a/client/src/api/reviews.ts +++ b/client/src/api/reviews.ts @@ -1,3 +1,5 @@ +import type { ApolloCache } from '@apollo/client'; + import { graphql } from '../generated/gql.js'; import type { DeleteReviewMutation, @@ -18,9 +20,20 @@ export const UPSERT_REVIEW = graphql(` id rating comment + createdAt + updatedAt } album { id + averageRating + reviewCount + myReview { + id + rating + comment + createdAt + updatedAt + } } } } @@ -32,7 +45,31 @@ export const DELETE_REVIEW = graphql(` deletedReviewId album { id + averageRating + reviewCount + myReview { + id + rating + comment + createdAt + updatedAt + } } } } `); + +/** + * Evict cached `searchAlbums` connections after a review is published, updated + * or deleted. + * + * Apollo already normalizes the returned `album { id averageRating reviewCount + * myReview { ... } }` fields into `Album:` before `update` runs, so + * `AlbumDetailPage` and `myCrate` update automatically. Evicting `searchAlbums` + * ensures returning to Discover refreshes rating-sorted order, `reviewed` + * filter membership and `reviewedCount` facets. + */ +export function updateCacheAfterReviewMutation(cache: ApolloCache): void { + cache.evict({ id: 'ROOT_QUERY', fieldName: 'searchAlbums' }); + cache.gc(); +} diff --git a/client/src/api/userIdentity.test.ts b/client/src/api/userIdentity.test.ts index 0fcd1e3..3263fe4 100644 --- a/client/src/api/userIdentity.test.ts +++ b/client/src/api/userIdentity.test.ts @@ -1,15 +1,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { getUserId, USER_ID_STORAGE_KEY } from './userIdentity.js'; +import { getUserId, resetFallbackUserId, USER_ID_STORAGE_KEY } from './userIdentity.js'; const generatedId = '550e8400-e29b-41d4-a716-446655440000'; +const secondGeneratedId = '660e8400-e29b-41d4-a716-446655440000'; beforeEach(() => { + resetFallbackUserId(); window.localStorage.clear(); vi.spyOn(crypto, 'randomUUID').mockReturnValue(generatedId); }); afterEach(() => { + resetFallbackUserId(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -44,4 +47,35 @@ describe('getUserId', () => { expect(getUserId()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f'); }); + + it('falls back to a stable in-memory UUID when localStorage.getItem throws', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new DOMException('Storage blocked', 'SecurityError'); + }); + vi.mocked(crypto.randomUUID) + .mockReturnValueOnce(generatedId) + .mockReturnValueOnce(secondGeneratedId); + + expect(getUserId()).toBe(generatedId); + expect(getUserId()).toBe(generatedId); + expect(crypto.randomUUID).toHaveBeenCalledTimes(1); + }); + + it('falls back to a stable in-memory UUID when localStorage.setItem throws', () => { + const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Quota exceeded', 'QuotaExceededError'); + }); + vi.mocked(crypto.randomUUID) + .mockReturnValueOnce(generatedId) + .mockReturnValueOnce(secondGeneratedId); + + expect(getUserId()).toBe(generatedId); + expect(getUserId()).toBe(generatedId); + expect(crypto.randomUUID).toHaveBeenCalledTimes(1); + + // Once storage becomes writable again, the same session UUID is persisted. + setItem.mockRestore(); + expect(getUserId()).toBe(generatedId); + expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId); + }); }); diff --git a/client/src/api/userIdentity.ts b/client/src/api/userIdentity.ts index dcc1eb2..f0047f5 100644 --- a/client/src/api/userIdentity.ts +++ b/client/src/api/userIdentity.ts @@ -3,6 +3,9 @@ export const USER_ID_STORAGE_KEY = 'crate.user-id'; const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +// Session-scoped fallback used when localStorage throws (e.g. privacy mode or quota errors). +let fallbackUserId: string | null = null; + function isUuid(value: string | null): value is string { return value !== null && UUID_PATTERN.test(value); } @@ -17,15 +20,52 @@ function createUuid(): string { return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } +function readStoredUserId(): { available: boolean; value: string | null } { + try { + return { available: true, value: window.localStorage.getItem(USER_ID_STORAGE_KEY) }; + } catch { + return { available: false, value: null }; + } +} + +function writeStoredUserId(userId: string): boolean { + try { + window.localStorage.setItem(USER_ID_STORAGE_KEY, userId); + return true; + } catch { + return false; + } +} + /** * This is a simulated identity, not authentication. It lets the API associate * a review or crate item with this browser without asking the user to sign in. + * Degrades to a stable in-memory UUID if `localStorage` is unavailable or full. */ export function getUserId(): string { - const existing = window.localStorage.getItem(USER_ID_STORAGE_KEY); - if (isUuid(existing)) return existing.toLowerCase(); + const stored = readStoredUserId(); + if (stored.available) { + if (isUuid(stored.value)) { + return stored.value.toLowerCase(); + } + + const userId = fallbackUserId ?? createUuid().toLowerCase(); + if (writeStoredUserId(userId)) { + fallbackUserId = null; + return userId; + } + + fallbackUserId = userId; + return userId; + } + + if (!fallbackUserId) { + fallbackUserId = createUuid().toLowerCase(); + } + return fallbackUserId; +} - const userId = createUuid(); - window.localStorage.setItem(USER_ID_STORAGE_KEY, userId); - return userId; +/** Clear the in-memory fallback identity (for test isolation). */ +export function resetFallbackUserId(): void { + fallbackUserId = null; } diff --git a/client/src/components/AlbumCard.tsx b/client/src/components/AlbumCard.tsx index 35484d4..ca06043 100644 --- a/client/src/components/AlbumCard.tsx +++ b/client/src/components/AlbumCard.tsx @@ -1,11 +1,14 @@ import './AlbumCard.css'; import type { AlbumSummary } from '../api/searchAlbums.js'; -import CrateButton from './CrateButton.js'; +import { appHref, useLocation } from '../router.js'; import AlbumCover from './AlbumCover.js'; +import CrateButton from './CrateButton.js'; +import Link from './Link.js'; export default function AlbumCard({ album }: { album: AlbumSummary }) { - const detailHref = `${import.meta.env.BASE_URL}album/${album.id}${window.location.search}`; + const location = useLocation(); + const detailHref = appHref(`/album/${album.id}`, location.search); const rating = album.reviewCount > 0 ? album.averageRating : null; return ( @@ -49,9 +52,9 @@ export default function AlbumCard({ album }: { album: AlbumSummary }) {

- + {album.title || 'Untitled album'} - +

{album.artists.map((artist) => artist.name).join(', ') || 'Artist unknown'} diff --git a/client/src/components/Link.tsx b/client/src/components/Link.tsx new file mode 100644 index 0000000..baba01c --- /dev/null +++ b/client/src/components/Link.tsx @@ -0,0 +1,48 @@ +import type { AnchorHTMLAttributes, MouseEvent } from 'react'; + +import { navigate } from '../router.js'; + +interface Props extends AnchorHTMLAttributes { + href: string; + replace?: boolean; +} + +export default function Link({ + href, + replace = false, + onClick, + target, + download, + children, + ...rest +}: Props) { + function handleClick(event: MouseEvent) { + onClick?.(event); + if ( + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.altKey || + event.ctrlKey || + event.shiftKey || + download !== undefined || + (target && target !== '_self') + ) { + return; + } + + const destination = new URL(href, window.location.href); + if (destination.origin !== window.location.origin) { + return; + } + + event.preventDefault(); + navigate(href, { replace }); + } + + return ( + + {children} + + ); +} diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx index ee0f923..b49e6ab 100644 --- a/client/src/components/ReviewForm.test.tsx +++ b/client/src/components/ReviewForm.test.tsx @@ -61,8 +61,25 @@ it.each([ const result = vi.fn(() => ({ data: { upsertReview: { - review: { id: '1', rating: 5, comment }, - album: { id: '1' }, + review: { + id: '1', + rating: 5, + comment, + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + album: { + id: '1', + averageRating: 5, + reviewCount: 1, + myReview: { + id: '1', + rating: 5, + comment, + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + }, }, }, })); @@ -165,8 +182,25 @@ it('blocks unchanged saves and updates availability when edits are reverted', as result: { data: { upsertReview: { - review: { id: 'r1', rating: 4, comment: '' }, - album: { id: '1' }, + review: { + id: 'r1', + rating: 4, + comment: '', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + album: { + id: '1', + averageRating: 4, + reviewCount: 1, + myReview: { + id: 'r1', + rating: 4, + comment: '', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + }, }, }, }, @@ -210,7 +244,12 @@ it('deletes an existing review and clears the form', async () => { }); const onChanged = vi.fn(() => refresh); const result = vi.fn(() => ({ - data: { deleteReview: { deletedReviewId: 'r1', album: { id: '1' } } }, + data: { + deleteReview: { + deletedReviewId: 'r1', + album: { id: '1', averageRating: null, reviewCount: 0, myReview: null }, + }, + }, })); render( ({ data: action === 'delete' - ? { deleteReview: { deletedReviewId: 'r1', album: { id: '1' } } } + ? { + deleteReview: { + deletedReviewId: 'r1', + album: { id: '1', averageRating: null, reviewCount: 0, myReview: null }, + }, + } : { upsertReview: { - review: { id: 'r1', rating: 4, comment }, - album: { id: '1' }, + review: { + id: 'r1', + rating: 4, + comment, + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + album: { + id: '1', + averageRating: 4, + reviewCount: 1, + myReview: { + id: 'r1', + rating: 4, + comment, + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + }, }, }, })); @@ -352,11 +413,38 @@ it.each(['publish', 'update', 'delete'])( result: { data: action === 'delete' - ? { deleteReview: { deletedReviewId: 'r1', album: { id: '1' } } } + ? { + deleteReview: { + deletedReviewId: 'r1', + album: { + id: '1', + averageRating: null, + reviewCount: 0, + myReview: null, + }, + }, + } : { upsertReview: { - review: { id: 'r1', rating: 4, comment: 'My review' }, - album: { id: '1' }, + review: { + id: 'r1', + rating: 4, + comment: 'My review', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + album: { + id: '1', + averageRating: 4, + reviewCount: 1, + myReview: { + id: 'r1', + rating: 4, + comment: 'My review', + createdAt: '2026-11-20T12:00:00.000Z', + updatedAt: '2026-11-20T12:00:00.000Z', + }, + }, }, }, }, diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx index ac1defe..b386e8c 100644 --- a/client/src/components/ReviewForm.tsx +++ b/client/src/components/ReviewForm.tsx @@ -3,7 +3,11 @@ import './ReviewForm.css'; import { useEffect, useRef, useState } from 'react'; import { useMutation } from '@apollo/client/react'; -import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js'; +import { + DELETE_REVIEW, + UPSERT_REVIEW, + updateCacheAfterReviewMutation, +} from '../api/reviews.js'; type ExistingReview = { id: string; rating: number; comment: string } | null; const MAX_COMMENT_LENGTH = 2000; @@ -24,8 +28,20 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { const statusRef = useRef(null); // Block repeated activations before React renders the busy state. const mutationInFlight = useRef(false); - const [saveReview] = useMutation(UPSERT_REVIEW); - const [deleteReview] = useMutation(DELETE_REVIEW); + const [saveReview] = useMutation(UPSERT_REVIEW, { + update(cache, { data }) { + if (data?.upsertReview.album) { + updateCacheAfterReviewMutation(cache); + } + }, + }); + const [deleteReview] = useMutation(DELETE_REVIEW, { + update(cache, { data }) { + if (data?.deleteReview.album) { + updateCacheAfterReviewMutation(cache); + } + }, + }); // The server trims outer whitespace before storing a comment. const unchanged = review !== null && rating === review.rating && comment.trim() === review.comment; diff --git a/client/src/components/RouteErrorBoundary.test.tsx b/client/src/components/RouteErrorBoundary.test.tsx new file mode 100644 index 0000000..4bab6aa --- /dev/null +++ b/client/src/components/RouteErrorBoundary.test.tsx @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; + +import RouteErrorBoundary from './RouteErrorBoundary.js'; + +function ThrowError({ error }: { error: Error }): never { + throw error; +} + +afterEach(() => { + window.sessionStorage.clear(); + vi.restoreAllMocks(); +}); + +describe('RouteErrorBoundary', () => { + it.each([ + new TypeError( + 'Failed to fetch dynamically imported module: https://example.com/assets/AlbumDetailPage-abc.js', + ), + new TypeError('error loading dynamically imported module'), + new TypeError('Importing a module script failed.'), + Object.assign(new Error('Chunk failed'), { name: 'ChunkLoadError' }), + ])('recognizes browser chunk load error %s and reloads once', (chunkError) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const onReload = vi.fn(); + + render( + + + , + ); + + expect(onReload).toHaveBeenCalledTimes(1); + expect(screen.getByRole('alert')).toHaveTextContent( + /newer version of Crate may have been deployed/i, + ); + }); + it('renders children when no error occurs', () => { + render( + +

+ Healthy route +
+ , + ); + + expect(screen.getByText('Healthy route')).toBeInTheDocument(); + }); + + it('reloads once on a stale chunk error and avoids reload loops on repeat failures', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const onReload = vi.fn(); + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /project2/assets/AlbumDetailPage-old.js', + ); + + const first = render( + + + , + ); + + expect(onReload).toHaveBeenCalledTimes(1); + first.unmount(); + + // A second failure on the same URL within the cooldown window must not auto-reload again. + render( + + + , + ); + + expect(onReload).toHaveBeenCalledTimes(1); + expect( + screen.getByRole('heading', { level: 1, name: 'Page could not be loaded' }), + ).toBeInTheDocument(); + expect(screen.getByRole('alert')).toHaveTextContent( + /newer version of Crate may have been deployed/i, + ); + + // Manual reload button still triggers reload when clicked. + fireEvent.click(screen.getByRole('button', { name: 'Reload page' })); + expect(onReload).toHaveBeenCalledTimes(2); + }); + + it('does not auto-reload when sessionStorage throws', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new DOMException('Blocked', 'SecurityError'); + }); + const onReload = vi.fn(); + + render( + + + , + ); + + expect(onReload).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Reload page' })).toBeInTheDocument(); + }); + + it('shows fallback without auto-reloading for non-chunk errors and resets on route change', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const onReload = vi.fn(); + + const { rerender } = render( + + + , + ); + + expect(onReload).not.toHaveBeenCalled(); + expect(screen.getByRole('alert')).toHaveTextContent( + /Something went wrong while loading this page/i, + ); + + rerender( + +
+ Recovered route +
+
, + ); + + expect(screen.getByText('Recovered route')).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/RouteErrorBoundary.tsx b/client/src/components/RouteErrorBoundary.tsx new file mode 100644 index 0000000..f1665e9 --- /dev/null +++ b/client/src/components/RouteErrorBoundary.tsx @@ -0,0 +1,105 @@ +import { Component, type ErrorInfo, type ReactNode } from 'react'; + +const RELOAD_GUARD_KEY = 'crate:chunk-reload'; +const RELOAD_COOLDOWN_MS = 30_000; + +const CHUNK_LOAD_ERROR_PATTERNS = [ + /Failed to fetch dynamically imported module/i, + /error loading dynamically imported module/i, + /Importing a module script failed/i, + /Loading chunk .+ failed/i, + /Unable to preload CSS/i, +]; + +function isChunkLoadError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + if (error.name === 'ChunkLoadError') return true; + return CHUNK_LOAD_ERROR_PATTERNS.some((pattern) => pattern.test(error.message)); +} + +function shouldReloadForChunkError(href: string, now = Date.now()): boolean { + try { + const raw = window.sessionStorage.getItem(RELOAD_GUARD_KEY); + if (raw) { + const parsed = JSON.parse(raw) as { href?: unknown; at?: unknown }; + if ( + parsed.href === href && + typeof parsed.at === 'number' && + now - parsed.at < RELOAD_COOLDOWN_MS + ) { + return false; + } + } + window.sessionStorage.setItem(RELOAD_GUARD_KEY, JSON.stringify({ href, at: now })); + return true; + } catch { + // If sessionStorage is unavailable, do not auto-reload because we cannot + // guard against reload loops; fall back to the manual reload UI instead. + return false; + } +} + +interface Props { + children: ReactNode; + resetKey: string; + onReload?: () => void; +} + +interface State { + error: Error | null; +} + +/** + * Catches route render and lazy-chunk failures (for example, stale hashed asset + * URLs after a new deploy). On a chunk-load error, reloads once per URL within + * a cooldown window via `sessionStorage`, and renders an accessible fallback + * with a manual reload button if the error persists. + */ +export default class RouteErrorBoundary extends Component { + state: State = { error: null }; + + static getDerivedStateFromError(error: Error): State { + return { error }; + } + + componentDidCatch(error: Error, _info: ErrorInfo): void { + if (isChunkLoadError(error) && shouldReloadForChunkError(window.location.href)) { + this.reloadPage(); + } + } + + componentDidUpdate(prevProps: Props): void { + if (this.state.error && prevProps.resetKey !== this.props.resetKey) { + this.setState({ error: null }); + } + } + + private reloadPage = (): void => { + if (this.props.onReload) { + this.props.onReload(); + } else { + window.location.reload(); + } + }; + + render(): ReactNode { + if (!this.state.error) { + return this.props.children; + } + + const chunkError = isChunkLoadError(this.state.error); + return ( +
+

Page could not be loaded

+

+ {chunkError + ? 'A newer version of Crate may have been deployed, or the connection was interrupted. Reload the page to try again.' + : 'Something went wrong while loading this page. Reload the page to try again.'} +

+ +
+ ); + } +} diff --git a/client/src/generated/gql.ts b/client/src/generated/gql.ts index e716b5e..3fcc5b8 100644 --- a/client/src/generated/gql.ts +++ b/client/src/generated/gql.ts @@ -18,8 +18,8 @@ type Documents = { "\n mutation AddToCrate($albumId: ID!) {\n addToCrate(albumId: $albumId) {\n item {\n id\n }\n album {\n id\n isInCrate\n }\n }\n }\n": typeof types.AddToCrateDocument, "\n mutation RemoveFromCrate($albumId: ID!) {\n removeFromCrate(albumId: $albumId) {\n removedAlbumId\n album {\n id\n isInCrate\n }\n }\n }\n": typeof types.RemoveFromCrateDocument, "\n query MyCrate($first: Int!, $after: String) {\n myCrate(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n addedAt\n album {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n averageRating\n reviewCount\n isInCrate\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n totalCount\n }\n }\n": typeof types.MyCrateDocument, - "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": typeof types.UpsertReviewDocument, - "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": typeof types.DeleteReviewDocument, + "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n": typeof types.UpsertReviewDocument, + "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n": typeof types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": typeof types.SearchAlbumsDocument, "\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": typeof types.SearchAlbumsPageDocument, "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": typeof types.MySearchHistoryDocument, @@ -31,8 +31,8 @@ const documents: Documents = { "\n mutation AddToCrate($albumId: ID!) {\n addToCrate(albumId: $albumId) {\n item {\n id\n }\n album {\n id\n isInCrate\n }\n }\n }\n": types.AddToCrateDocument, "\n mutation RemoveFromCrate($albumId: ID!) {\n removeFromCrate(albumId: $albumId) {\n removedAlbumId\n album {\n id\n isInCrate\n }\n }\n }\n": types.RemoveFromCrateDocument, "\n query MyCrate($first: Int!, $after: String) {\n myCrate(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n addedAt\n album {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n averageRating\n reviewCount\n isInCrate\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n totalCount\n }\n }\n": types.MyCrateDocument, - "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": types.UpsertReviewDocument, - "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": types.DeleteReviewDocument, + "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n": types.UpsertReviewDocument, + "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n": types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": types.SearchAlbumsDocument, "\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": types.SearchAlbumsPageDocument, "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": types.MySearchHistoryDocument, @@ -73,11 +73,11 @@ export function graphql(source: "\n query MyCrate($first: Int!, $after: String) /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n"): (typeof documents)["\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n"]; +export function graphql(source: "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n"): (typeof documents)["\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n"]; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n"): (typeof documents)["\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n"]; +export function graphql(source: "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n"): (typeof documents)["\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n averageRating\n reviewCount\n myReview {\n id\n rating\n comment\n createdAt\n updatedAt\n }\n }\n }\n }\n"]; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ diff --git a/client/src/generated/graphql.ts b/client/src/generated/graphql.ts index 18bff5d..42b459a 100644 --- a/client/src/generated/graphql.ts +++ b/client/src/generated/graphql.ts @@ -64,14 +64,14 @@ export type UpsertReviewMutationVariables = Exact<{ }>; -export type UpsertReviewMutation = { upsertReview: { review: { id: string, rating: number, comment: string }, album: { id: string } } }; +export type UpsertReviewMutation = { upsertReview: { review: { id: string, rating: number, comment: string, createdAt: string, updatedAt: string }, album: { id: string, averageRating: number | null, reviewCount: number, myReview: { id: string, rating: number, comment: string, createdAt: string, updatedAt: string } | null } } }; export type DeleteReviewMutationVariables = Exact<{ id: string | number; }>; -export type DeleteReviewMutation = { deleteReview: { deletedReviewId: string, album: { id: string } } }; +export type DeleteReviewMutation = { deleteReview: { deletedReviewId: string, album: { id: string, averageRating: number | null, reviewCount: number, myReview: { id: string, rating: number, comment: string, createdAt: string, updatedAt: string } | null } } }; export type SearchAlbumsQueryVariables = Exact<{ input: AlbumSearchInput; @@ -113,8 +113,8 @@ export const AlbumDetailDocument = {"kind":"Document","definitions":[{"kind":"Op export const AddToCrateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AddToCrate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"addToCrate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"albumId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"item"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}}]}}]} as unknown as DocumentNode; export const RemoveFromCrateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RemoveFromCrate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"removeFromCrate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"albumId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"removedAlbumId"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}}]}}]} as unknown as DocumentNode; export const MyCrateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyCrate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myCrate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"addedAt"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode; -export const UpsertReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpsertReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpsertReviewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"review"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; -export const DeleteReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedReviewId"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; +export const UpsertReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpsertReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpsertReviewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"review"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"myReview"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]}}]} as unknown as DocumentNode; +export const DeleteReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedReviewId"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"myReview"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]}}]} as unknown as DocumentNode; export const SearchAlbumsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbums"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"genreFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"genre"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"decadeFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"decade"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"countryFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"countryCode"}},{"kind":"Field","name":{"kind":"Name","value":"countryName"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"reviewedCount"}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; export const SearchAlbumsPageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbumsPage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; export const MySearchHistoryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"mySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"query"}},{"kind":"Field","name":{"kind":"Name","value":"lastSearchedAt"}}]}}]}}]} as unknown as DocumentNode; diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index 35b0f77..e6f0601 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -7,6 +7,7 @@ import { SEARCH_ALBUMS_PAGE, type AlbumSearchInput, } from '../api/searchAlbums.js'; +import { stripBasePath, subscribeBeforeNavigate, useLocation } from '../router.js'; import { clearSearchReturnState, readSearchReturnState, @@ -17,7 +18,29 @@ import { useSearchState } from './useSearchState.js'; const PAGE_SIZE = 20; const AUTOMATIC_PAGE_LIMIT = 2; +interface PaginationState { + visitKey: string; + visibleCount: number; + automaticPages: number; + loadingMore: boolean; + pageError: boolean; +} + +function createPagination(visitKey: string, visibleCount = PAGE_SIZE): PaginationState { + return { + visitKey, + visibleCount, + automaticPages: Math.min( + AUTOMATIC_PAGE_LIMIT, + Math.max(0, Math.ceil(visibleCount / PAGE_SIZE) - 1), + ), + loadingMore: false, + pageError: false, + }; +} + export function useAlbumSearch() { + const location = useLocation(); const { state, setQuery, @@ -58,32 +81,30 @@ export function useAlbumSearch() { fetchPolicy: 'cache-first', }); - const key = JSON.stringify(input); - const [pagination, setPagination] = useState({ - key, - visibleCount: PAGE_SIZE, - automaticPages: 0, - loadingMore: false, - pageError: false, + const inputKey = JSON.stringify(input); + const visitKey = `${location.key}:${inputKey}`; + const pageInfo = data?.searchAlbums.pageInfo; + const edges = data?.searchAlbums.edges ?? []; + + const [paginationState, setPaginationState] = useState(() => { + if (savedReturnState && edges.length >= savedReturnState.visibleCount) { + return createPagination( + visitKey, + Math.min(savedReturnState.visibleCount, edges.length), + ); + } + return createPagination(visitKey); }); - // 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, - }); - } + // Derive fresh pagination whenever the search visit changes instead of + // mutating React state during render. + const pagination = + paginationState.visitKey === visitKey ? paginationState : createPagination(visitKey); 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 = @@ -95,23 +116,25 @@ export function useAlbumSearch() { if ( !hasNextPage || loading || - pagesInFlight.current.has(key) || + pagesInFlight.current.has(inputKey) || (automatic && !canLoadAutomatically) ) { return; } - const nextPagination = { - ...pagination, - automaticPages: pagination.automaticPages + (automatic ? 1 : 0), - }; + const nextAutomaticPages = 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, - ); + setPaginationState((current) => { + const active = current.visitKey === visitKey ? current : pagination; + return active === pagination + ? { + ...active, + automaticPages: nextAutomaticPages, + visibleCount: active.visibleCount + PAGE_SIZE, + } + : current; + }); return; } @@ -120,9 +143,13 @@ export function useAlbumSearch() { } // Guard clicks and observer notifications before the next render. - pagesInFlight.current.add(key); - const pendingPage = { ...pagination, loadingMore: true, pageError: false }; - setPagination(pendingPage); + pagesInFlight.current.add(inputKey); + const pendingPage: PaginationState = { + ...pagination, + loadingMore: true, + pageError: false, + }; + setPaginationState(pendingPage); // A lighter query: the count and facets from page one stay in the cache. void fetchMore({ @@ -131,32 +158,33 @@ export function useAlbumSearch() { }) .then(() => { // Late pages stay cached but must not expand a different search visit. - setPagination((current) => + setPaginationState((current) => current === pendingPage ? { ...current, visibleCount: current.visibleCount + PAGE_SIZE, - automaticPages: nextPagination.automaticPages, + automaticPages: nextAutomaticPages, loadingMore: false, } : current, ); }) .catch(() => { - setPagination((current) => + setPaginationState((current) => current === pendingPage ? { ...current, pageError: true, loadingMore: false } : current, ); }) .finally(() => { - pagesInFlight.current.delete(key); + pagesInFlight.current.delete(inputKey); }); }, [ hasNextPage, loading, - key, + inputKey, + visitKey, fetchMore, input, pageInfo, @@ -203,57 +231,24 @@ export function useAlbumSearch() { const facets = (data ?? previousData)?.searchAlbums; const visibleAlbumCount = Math.min(pagination.visibleCount, edges.length); + // Save visible count and scroll position right before SPA navigation to an album. useEffect(() => { - const basePath = import.meta.env.BASE_URL.replace(/\/$/, ''); - const albumPathPrefix = `${basePath}/album/`; - - function saveBeforeOpeningAlbum(event: MouseEvent) { - if ( - event.defaultPrevented || - event.button !== 0 || - event.altKey || - event.ctrlKey || - event.metaKey || - event.shiftKey || - !(event.target instanceof Element) - ) { - return; - } - - const link = event.target.closest('a[href]'); - if (!link || link.hasAttribute('download')) return; - const target = link.getAttribute('target'); - if (target && target !== '_self') return; - - const destination = new URL(link.href, window.location.href); - if ( - destination.origin !== window.location.origin || - !destination.pathname.startsWith(albumPathPrefix) - ) { - return; - } + return subscribeBeforeNavigate((target) => { + if (!/^\/album\/\d+$/.test(stripBasePath(target.pathname))) return; saveSearchReturnState({ url: `${window.location.pathname}${window.location.search}`, visibleCount: visibleAlbumCount, scrollY: Math.max(0, window.scrollY), }); - } - - document.addEventListener('click', saveBeforeOpeningAlbum); - return () => document.removeEventListener('click', saveBeforeOpeningAlbum); + }); }, [visibleAlbumCount]); + // Restore scroll position (and any uncached pages after a hard reload or cache + // eviction) when returning from an album detail page. useEffect(() => { const saved = returnState.current; - if ( - !saved || - !data || - loading || - pagination.key !== key || - pagination.loadingMore || - pagination.pageError - ) { + if (!saved || !data || loading || pagination.loadingMore || pagination.pageError) { return; } @@ -265,26 +260,17 @@ export function useAlbumSearch() { const restoredCount = Math.min(saved.visibleCount, edges.length); returnState.current = null; clearSearchReturnState(); - setPagination((current) => - current.key === key - ? { - ...current, - visibleCount: restoredCount, - automaticPages: Math.min( - AUTOMATIC_PAGE_LIMIT, - Math.max(0, Math.ceil(restoredCount / PAGE_SIZE) - 1), - ), - } - : current, - ); + if (pagination.visibleCount < restoredCount) { + setPaginationState(createPagination(visitKey, restoredCount)); + } window.requestAnimationFrame(() => window.scrollTo(0, saved.scrollY)); }, [ data, loading, - pagination.key, pagination.loadingMore, pagination.pageError, - key, + pagination.visibleCount, + visitKey, edges.length, pageInfo?.hasNextPage, loadMore, diff --git a/client/src/hooks/useSearchHistory.ts b/client/src/hooks/useSearchHistory.ts index c2b15a0..f2658f9 100644 --- a/client/src/hooks/useSearchHistory.ts +++ b/client/src/hooks/useSearchHistory.ts @@ -14,7 +14,7 @@ export function useSearchHistory() { error: loadError, refetch, } = useQuery(MY_SEARCH_HISTORY, { - fetchPolicy: 'network-only', + fetchPolicy: 'cache-first', }); const [record] = useMutation(RECORD_SEARCH); const [clear, { client }] = useMutation(CLEAR_SEARCH_HISTORY); diff --git a/client/src/hooks/useSearchState.ts b/client/src/hooks/useSearchState.ts index 449ba3d..f767ba5 100644 --- a/client/src/hooks/useSearchState.ts +++ b/client/src/hooks/useSearchState.ts @@ -1,6 +1,7 @@ import { useCallback, useSyncExternalStore } from 'react'; import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js'; +import { navigate, subscribeLocation } from '../router.js'; /** * Search state lives in the URL, so a reload, back and forward, and a pasted @@ -155,11 +156,6 @@ export function serializeSearchState( 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; @@ -174,26 +170,6 @@ function readSearchState(): SearchState { 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, explicitSort = false): void { const current = window.location.search; const search = serializeSearchState(next, current, explicitSort); @@ -201,11 +177,9 @@ function writeSearchState(next: SearchState, explicitSort = false): void { 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(); + navigate(url, { scrollToTop: false }); } /** @@ -214,7 +188,7 @@ function writeSearchState(next: SearchState, explicitSort = false): void { * the searches the way a user expects. */ export function useSearchState() { - const state = useSyncExternalStore(subscribe, readSearchState, readSearchState); + const state = useSyncExternalStore(subscribeLocation, readSearchState, readSearchState); const setSearch = useCallback((patch: Partial) => { const next = { ...readSearchState(), ...patch }; diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx index 7131aee..7a7605f 100644 --- a/client/src/pages/AlbumDetailPage.tsx +++ b/client/src/pages/AlbumDetailPage.tsx @@ -5,9 +5,11 @@ import { useEffect, useRef, useState } from 'react'; import { useQuery } from '@apollo/client/react'; import { ALBUM_DETAIL } from '../api/albumDetail.js'; -import ReviewForm from '../components/ReviewForm.js'; -import CrateButton from '../components/CrateButton.js'; import AlbumCover from '../components/AlbumCover.js'; +import CrateButton from '../components/CrateButton.js'; +import Link from '../components/Link.js'; +import ReviewForm from '../components/ReviewForm.js'; +import { appHref, useLocation } from '../router.js'; const REVIEW_PAGE_SIZE = 10; @@ -27,10 +29,11 @@ export default function AlbumDetailPage({ id }: { id: string }) { const [reviewsError, setReviewsError] = useState(null); const reviewStatusRef = useRef(null); const reviewButtonHadFocus = useRef(false); + const location = useLocation(); const { data, loading, error, refetch, fetchMore } = useQuery(ALBUM_DETAIL, { variables: { id, reviewFirst: REVIEW_PAGE_SIZE, reviewAfter: null }, }); - const discoveryHref = `${import.meta.env.BASE_URL}${window.location.search}`; + const discoveryHref = appHref('/', location.search); useEffect(() => { if ( @@ -96,9 +99,9 @@ export default function AlbumDetailPage({ id }: { id: string }) { if (error || !data?.album) { return (
- + ← Back to Discover - +

Album unavailable

We could not load this album. Please try again.

@@ -115,9 +118,9 @@ export default function AlbumDetailPage({ id }: { id: string }) { return (
- + ← Back to Discover - +
)} diff --git a/client/src/pages/DiscoveryPage.tsx b/client/src/pages/DiscoveryPage.tsx new file mode 100644 index 0000000..40eb00a --- /dev/null +++ b/client/src/pages/DiscoveryPage.tsx @@ -0,0 +1,73 @@ +import ResultsLayout from '../components/ResultsLayout.js'; +import SearchForm from '../components/SearchForm.js'; +import { useAlbumSearch } from '../hooks/useAlbumSearch.js'; +import { useSearchHistory } from '../hooks/useSearchHistory.js'; + +export default function DiscoveryPage() { + const search = useAlbumSearch(); + const history = useSearchHistory(); + + function submitSearch(query: string) { + search.search(query); + history.recordSearch(query); + } + + return ( +
+
+
+

Your next favorite is in here

+

+ Music worth +
holding onto. +

+

+ Search, rate and collect albums you’ll want to return to. +

+ +

+ Photo by{' '} + + Kevin McCutcheon on Unsplash + +

+
+
+
+ +
+
+ ); +} diff --git a/client/src/router.test.tsx b/client/src/router.test.tsx new file mode 100644 index 0000000..6de4b92 --- /dev/null +++ b/client/src/router.test.tsx @@ -0,0 +1,485 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MockedProvider } from '@apollo/client/testing/react'; + +import App from './App.js'; +import { ALBUM_DETAIL } from './api/albumDetail.js'; +import { cache } from './api/client.js'; +import { MY_CRATE } from './api/crate.js'; +import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from './api/searchAlbums.js'; +import { MY_SEARCH_HISTORY } from './api/searchHistory.js'; +import { clearSearchReturnState } from './hooks/searchReturnState.js'; +import { appHref, stripBasePath } from './router.js'; + +const albumNode = (id: string, title = `Album ${id}`) => ({ + __typename: 'Album' as const, + id, + title, + releaseYear: 1969, + musicBrainzReleaseGroupId: null, + artists: [{ __typename: 'Artist' as const, id: 'a1', name: 'The Beatles' }], + genres: [{ __typename: 'Genre' as const, id: 'g1', name: 'Rock' }], + averageRating: 4.5, + reviewCount: 12, + isInCrate: true, +}); + +const albumDetailResult = { + data: { + album: { + ...albumNode('1', 'Abbey Road'), + tracks: [ + { + __typename: 'Track' as const, + id: 't1', + title: 'Come Together', + trackNumber: 1, + durationSeconds: 259, + }, + ], + myReview: null, + reviews: { + edges: [], + totalCount: 0, + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, +}; + +afterEach(() => { + clearSearchReturnState(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('router helpers', () => { + it('strips the /project2 base path cleanly without matching sibling prefixes', () => { + expect(stripBasePath('/project2', '/project2/')).toBe('/'); + expect(stripBasePath('/project2/', '/project2/')).toBe('/'); + expect(stripBasePath('/project2/crate', '/project2/')).toBe('/crate'); + expect(stripBasePath('/project2/crate/', '/project2/')).toBe('/crate'); + expect(stripBasePath('/project2/album/42', '/project2/')).toBe('/album/42'); + expect(stripBasePath('/project20/crate', '/project2/')).toBe('/project20/crate'); + }); + + it('builds app URLs under BASE_URL', () => { + expect(appHref('/')).toBe(import.meta.env.BASE_URL); + expect(appHref('/', '?q=blue')).toBe(`${import.meta.env.BASE_URL}?q=blue`); + expect(appHref('/crate')).toBe( + `${import.meta.env.BASE_URL.replace(/\/$/, '')}/crate`, + ); + expect(appHref('/album/1', '?q=blue')).toBe( + `${import.meta.env.BASE_URL}album/1?q=blue`, + ); + }); +}); + +describe('client-side SPA routing', () => { + it('navigates between Discover, Album Detail, and Your Crate while preserving Apollo cache', async () => { + const scrollTo = vi.fn(); + vi.stubGlobal('scrollTo', scrollTo); + window.history.replaceState({}, '', appHref('/', '?q=abbey')); + + const searchResult = vi.fn(() => ({ + data: { + searchAlbums: { + edges: [{ cursor: 'c1', node: albumNode('1', 'Abbey Road') }], + totalCount: 1, + genreFacets: [], + decadeFacets: [], + countryFacets: [], + reviewedCount: 1, + pageInfo: { hasNextPage: false, endCursor: 'c1' }, + }, + }, + })); + const historyResult = vi.fn(() => ({ + data: { mySearchHistory: [] }, + })); + const crateResult = vi.fn(() => ({ + data: { + myCrate: { + edges: [ + { + cursor: 'crate-1', + node: { + __typename: 'CrateItem' as const, + id: 'ci1', + addedAt: '2026-11-20T12:00:00.000Z', + album: albumNode('1', 'Abbey Road'), + }, + }, + ], + pageInfo: { hasNextPage: false, endCursor: 'crate-1' }, + totalCount: 1, + }, + }, + })); + + render( + + + , + ); + + const albumLink = await screen.findByRole('link', { name: 'Abbey Road' }); + expect(searchResult).toHaveBeenCalledTimes(1); + expect(historyResult).toHaveBeenCalledTimes(1); + + // Modifier clicks keep native browser behavior and do not trigger SPA navigation. + fireEvent.click(albumLink, { ctrlKey: true }); + expect(window.location.pathname).toBe(appHref('/')); + + // Discover -> Album Detail (client-side) + fireEvent.click(albumLink); + expect(window.location.pathname).toBe(appHref('/album/1')); + expect(window.location.search).toBe('?q=abbey'); + expect( + await screen.findByRole('heading', { level: 1, name: 'Abbey Road' }), + ).toBeInTheDocument(); + expect(scrollTo).toHaveBeenCalledWith(0, 0); + + // Album Detail -> Your Crate (client-side) + fireEvent.click(screen.getByRole('link', { name: 'Your crate' })); + expect(window.location.pathname).toBe(appHref('/crate')); + expect( + await screen.findByRole('heading', { level: 1, name: 'Your crate' }), + ).toBeInTheDocument(); + expect( + await screen.findByRole('heading', { level: 3, name: 'Abbey Road' }), + ).toBeInTheDocument(); + expect(crateResult).toHaveBeenCalledTimes(1); + + // Browser Back -> Discover (Apollo cache reused, no refetch!) + window.history.replaceState({}, '', appHref('/', '?q=abbey')); + await act(async () => { + window.dispatchEvent(new PopStateEvent('popstate')); + }); + + expect(await screen.findByRole('link', { name: 'Abbey Road' })).toBeInTheDocument(); + // Both search results and search history were served from InMemoryCache. + expect(searchResult).toHaveBeenCalledTimes(1); + expect(historyResult).toHaveBeenCalledTimes(1); + }); + + it('restores loaded pages from Apollo cache and scroll position on return from Album Detail', async () => { + const scrollTo = vi.fn(); + vi.stubGlobal('scrollTo', scrollTo); + vi.stubGlobal('scrollY', 1450); + window.history.replaceState({}, '', appHref('/', '?q=the')); + + const pageOne = Array.from({ length: 20 }, (_, i) => albumNode(String(i + 1))); + const pageTwo = Array.from({ length: 20 }, (_, i) => albumNode(String(i + 21))); + + const firstPageMock = vi.fn(() => ({ + data: { + searchAlbums: { + edges: pageOne.map((node) => ({ cursor: `c-${node.id}`, node })), + totalCount: 40, + genreFacets: [], + decadeFacets: [], + countryFacets: [], + reviewedCount: 40, + pageInfo: { hasNextPage: true, endCursor: 'c-20' }, + }, + }, + })); + const secondPageMock = vi.fn(() => ({ + data: { + searchAlbums: { + edges: pageTwo.map((node) => ({ cursor: `c-${node.id}`, node })), + pageInfo: { hasNextPage: false, endCursor: 'c-40' }, + }, + }, + })); + + render( + + + , + ); + + await screen.findByRole('link', { name: 'Album 20' }); + fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + await screen.findByRole('link', { name: 'Album 40' }); + + // Open album 1 while scrolled down. + fireEvent.click(screen.getByRole('link', { name: 'Album 1' })); + expect( + await screen.findByRole('heading', { level: 1, name: 'Abbey Road' }), + ).toBeInTheDocument(); + + // Return via Back to Discover link. + fireEvent.click(screen.getByRole('link', { name: '← Back to Discover' })); + expect(await screen.findByRole('link', { name: 'Album 40' })).toBeInTheDocument(); + expect(screen.getAllByRole('article')).toHaveLength(40); + await waitFor(() => expect(scrollTo).toHaveBeenCalledWith(0, 1450)); + + // Neither page 1 nor page 2 had to be re-fetched! + expect(firstPageMock).toHaveBeenCalledTimes(1); + expect(secondPageMock).toHaveBeenCalledTimes(1); + }); + + it('moves focus to
on pathname changes, not initial render or query-only changes', async () => { + const pushStateSpy = vi.spyOn(window.history, 'pushState'); + const scrollTo = vi.fn(); + vi.stubGlobal('scrollTo', scrollTo); + window.history.replaceState({ previous: true }, '', appHref('/', '?q=abbey')); + + render( + + + , + ); + + await screen.findByRole('link', { name: 'Abbey Road' }); + // Initial render must not steal focus onto
. + expect(document.activeElement).not.toBe(document.getElementById('main')); + + // Query-only change (changing sort) must not steal focus from the sort select. + const sortSelect = screen.getByLabelText('Sort by'); + sortSelect.focus(); + fireEvent.change(sortSelect, { target: { value: 'TITLE_ASC' } }); + expect(window.location.search).toContain('sort=TITLE_ASC'); + expect(document.activeElement).toBe(sortSelect); + expect(pushStateSpy).toHaveBeenCalledWith( + null, + '', + expect.stringContaining('sort=TITLE_ASC'), + ); + + // Pathname change (clicking an album card link) moves focus to
. + const updatedAlbumLink = await screen.findByRole('link', { name: 'Abbey Road' }); + updatedAlbumLink.focus(); + fireEvent.click(updatedAlbumLink); + expect( + await screen.findByRole('heading', { level: 1, name: 'Abbey Road' }), + ).toBeInTheDocument(); + await waitFor(() => { + expect(document.activeElement).toBe(document.getElementById('main')); + }); + expect(pushStateSpy).toHaveBeenLastCalledWith( + null, + '', + expect.stringContaining('/album/1'), + ); + }); + + it('does not reset Discover pagination on hash-only popstate (skip link)', async () => { + window.history.replaceState({}, '', appHref('/', '?q=the')); + + const pageOne = Array.from({ length: 20 }, (_, i) => albumNode(String(i + 1))); + const pageTwo = Array.from({ length: 20 }, (_, i) => albumNode(String(i + 21))); + + render( + ({ cursor: `c-${node.id}`, node })), + totalCount: 40, + genreFacets: [], + decadeFacets: [], + countryFacets: [], + reviewedCount: 40, + pageInfo: { hasNextPage: true, endCursor: 'c-20' }, + }, + }, + }, + maxUsageCount: 3, + }, + { + request: { + query: SEARCH_ALBUMS_PAGE, + variables: { + input: { query: 'the', sort: 'RELEVANCE' }, + first: 20, + after: 'c-20', + }, + }, + result: { + data: { + searchAlbums: { + edges: pageTwo.map((node) => ({ cursor: `c-${node.id}`, node })), + pageInfo: { hasNextPage: false, endCursor: 'c-40' }, + }, + }, + }, + maxUsageCount: 3, + }, + { + request: { query: MY_SEARCH_HISTORY }, + result: { data: { mySearchHistory: [] } }, + maxUsageCount: 3, + }, + ]} + > + + , + ); + + await screen.findByRole('link', { name: 'Album 20' }); + fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + await screen.findByRole('link', { name: 'Album 40' }); + expect(screen.getAllByRole('article')).toHaveLength(40); + + // Simulate clicking : browser changes hash and dispatches popstate. + window.history.replaceState({}, '', `${appHref('/', '?q=the')}#main`); + await act(async () => { + window.dispatchEvent(new PopStateEvent('popstate')); + }); + + expect(screen.getAllByRole('article')).toHaveLength(40); + }); +}); diff --git a/client/src/router.ts b/client/src/router.ts new file mode 100644 index 0000000..08b8c23 --- /dev/null +++ b/client/src/router.ts @@ -0,0 +1,178 @@ +import { useSyncExternalStore } from 'react'; + +export interface AppLocation { + pathname: string; + search: string; + hash: string; + /** Monotonic counter incremented on every navigation so search visits stay distinct. */ + key: number; +} + +type Listener = () => void; +type BeforeNavigateListener = (to: URL) => void; + +const listeners = new Set(); +const beforeNavigateListeners = new Set(); +let popstateBound = false; +let locationKey = 0; + +let cachedHref: string | null = null; +let cachedLocation: AppLocation = { + pathname: window.location.pathname, + search: window.location.search, + hash: window.location.hash, + key: locationKey, +}; + +export function getLocation(): AppLocation { + const href = `${window.location.pathname}${window.location.search}${window.location.hash}`; + if (href !== cachedHref || cachedLocation.key !== locationKey) { + cachedHref = href; + cachedLocation = { + pathname: window.location.pathname, + search: window.location.search, + hash: window.location.hash, + key: locationKey, + }; + } + return cachedLocation; +} + +function notifyLocation(): void { + cachedHref = null; + for (const listener of listeners) listener(); +} + +function handlePopState(): void { + const samePathAndSearch = + window.location.pathname === cachedLocation.pathname && + window.location.search === cachedLocation.search; + if (samePathAndSearch && window.location.hash !== cachedLocation.hash) { + // Hash-only popstate (e.g. clicking the `#main` skip link) must not bump + // locationKey or reset Discover's loaded pagination. + cachedHref = `${window.location.pathname}${window.location.search}${window.location.hash}`; + cachedLocation = { + ...cachedLocation, + hash: window.location.hash, + }; + return; + } + locationKey += 1; + notifyLocation(); +} + +export function subscribeLocation(listener: Listener): () => void { + if (!popstateBound) { + window.addEventListener('popstate', handlePopState); + popstateBound = true; + } + listeners.add(listener); + + return () => { + listeners.delete(listener); + if (listeners.size === 0) { + window.removeEventListener('popstate', handlePopState); + popstateBound = false; + } + }; +} + +export function subscribeBeforeNavigate(listener: BeforeNavigateListener): () => void { + beforeNavigateListeners.add(listener); + return () => { + beforeNavigateListeners.delete(listener); + }; +} + +export function useLocation(): AppLocation { + return useSyncExternalStore(subscribeLocation, getLocation, getLocation); +} + +/** + * Base path without trailing slash (e.g. `"/project2"` in production, `""` at `/`). + */ +export function getBasePath(): string { + return import.meta.env.BASE_URL.replace(/\/$/, ''); +} + +/** + * Strip the configured Vite base path so route matching works identically under + * `/project2/...` (production/preview) and `/...` (unit tests). + */ +export function stripBasePath(pathname: string, basePath = getBasePath()): string { + const normalizedBase = basePath.replace(/\/$/, ''); + let stripped = pathname; + if ( + normalizedBase && + (pathname === normalizedBase || pathname.startsWith(`${normalizedBase}/`)) + ) { + stripped = pathname.slice(normalizedBase.length) || '/'; + } + if (stripped.length > 1) { + stripped = stripped.replace(/\/+$/, ''); + } + return stripped || '/'; +} + +/** + * Build an in-app href under `import.meta.env.BASE_URL`. + */ +export function appHref(routePath: string, search = ''): string { + if (routePath === '/' || routePath === '') { + return `${import.meta.env.BASE_URL}${search}`; + } + const normalized = routePath.startsWith('/') ? routePath : `/${routePath}`; + return `${getBasePath()}${normalized}${search}`; +} + +export interface NavigateOptions { + replace?: boolean; + scrollToTop?: boolean; +} + +function safeScrollToTop(): void { + if (typeof window.scrollTo !== 'function') return; + try { + window.scrollTo(0, 0); + } catch { + // jsdom does not implement window.scrollTo. + } +} + +/** + * Push (or replace) an in-app URL via the History API without reloading the document. + */ +export function navigate(to: string, options: NavigateOptions = {}): void { + const { replace = false, scrollToTop = true } = options; + const target = new URL(to, window.location.href); + if (target.origin !== window.location.origin) { + window.location.assign(target.href); + return; + } + + const nextUrl = `${target.pathname}${target.search}${target.hash}`; + const currentUrl = `${window.location.pathname}${window.location.search}${window.location.hash}`; + if (nextUrl === currentUrl) return; + + const pathnameChanged = target.pathname !== window.location.pathname; + const pathOrSearchChanged = pathnameChanged || target.search !== window.location.search; + + for (const listener of beforeNavigateListeners) { + listener(target); + } + + if (replace) { + window.history.replaceState(window.history.state, '', nextUrl); + } else { + window.history.pushState(null, '', nextUrl); + } + + if (pathOrSearchChanged) { + locationKey += 1; + } + notifyLocation(); + + if (scrollToTop && pathnameChanged) { + safeScrollToTop(); + } +} diff --git a/client/vite.config.ts b/client/vite.config.ts index 5810ede..5f22a29 100644 --- a/client/vite.config.ts +++ b/client/vite.config.ts @@ -9,7 +9,6 @@ export default defineConfig({ port: 5173, proxy: { // Matches Apache's production /graphql route; the local API uses port 3001. - // TODO(#6): Confirm this port when the backend is available in this checkout. '/graphql': 'http://127.0.0.1:3001', }, },