` 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.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.'}
+
+
+ Reload page
+
+
+ );
+ }
+}
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/CratePage.tsx b/client/src/pages/CratePage.tsx
index 362d21c..f997bcb 100644
--- a/client/src/pages/CratePage.tsx
+++ b/client/src/pages/CratePage.tsx
@@ -5,11 +5,13 @@ import { useQuery } from '@apollo/client/react';
import { MY_CRATE } from '../api/crate.js';
import AlbumCard from '../components/AlbumCard.js';
+import Link from '../components/Link.js';
+import { appHref } from '../router.js';
const PAGE_SIZE = 20;
export default function CratePage() {
- const discoveryHref = import.meta.env.BASE_URL;
+ const discoveryHref = appHref('/');
const [loadingMore, setLoadingMore] = useState(false);
const [pageError, setPageError] = useState(false);
const [retrying, setRetrying] = useState(false);
@@ -94,9 +96,9 @@ export default function CratePage() {
Add an album from the search results or an album page and it will appear
here.
-
+
Discover albums
-
+
)}
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',
},
},