Skip to content

Conversation

erikhfj
Copy link
Member

@erikhfj erikhfj commented Nov 25, 2026

Closes #131

What was done

  • Client-side SPA routing (client/src/router.ts, client/src/components/Link.tsx, client/src/App.tsx, AlbumCard.tsx, AlbumDetailPage.tsx, CratePage.tsx, useSearchState.ts):
    • Replaced full-page <a href> reloads with a lightweight, zero-dependency History API router under /project2/ supporting Discover (/), Album Detail (/album/:id), and Your Crate (/crate).
    • Preserves Apollo InMemoryCache across navigations (including mySearchHistory switched to cache-first in useSearchHistory.ts), deep links, reloads, browser back/forward, modifier-key native link behavior, scroll reset on forward route transitions, and warm-cache loaded-page + scroll restoration on return to Discover (replacing the global document click listener in useAlbumSearch.ts with subscribeBeforeNavigate).
  • Review mutation Apollo cache updates (client/src/api/reviews.ts, ReviewForm.tsx, client/src/generated/):
    • Updated UPSERT_REVIEW and DELETE_REVIEW to select updated album { id averageRating reviewCount myReview { id rating comment createdAt updatedAt } } and regenerated GraphQL types.
    • Added updateCacheAfterReviewMutation to immediately sync normalized Album records (updating AlbumDetailPage and myCrate views in place) and evict cached searchAlbums entries so Discover reflects rating/count/facet/sort changes on return.
  • Storage resilience (client/src/api/userIdentity.ts, userIdentity.test.ts):
    • Wrapped localStorage.getItem / setItem in try/catch with a session-scoped in-memory UUID fallback so blocked/full storage never breaks GraphQL requests.
  • Client state & code hygiene (client/src/api/client.ts, useAlbumSearch.ts, DiscoveryPage.tsx, vite.config.ts):
    • Extracted shared mergeCursorConnection helper used by both searchAlbums and myCrate.
    • Eliminated render-time setPagination in useAlbumSearch.ts by deriving pagination per search visitKey.
    • Extracted DiscoveryPage from App.tsx to client/src/pages/DiscoveryPage.tsx.
    • Removed stale // TODO(#6) comment in client/vite.config.ts.

What was tested

  • pnpm codegen && pnpm format:check && pnpm lint && pnpm typecheck && pnpm test && pnpm build
    • Client: 23/23 test files, 229/229 tests passed (including new router.test.tsx, client.test.ts crate & review cache tests, userIdentity.test.ts storage fallback tests).
    • Server: 9/9 unit test files, 88/88 passed (56 PG integration tests skipped locally).
    • ESLint: 0 errors, 0 warnings.
    • Bundle sizes (client/dist/assets/*.js, CI budget <= 512,000 B): index 390,435 B (630 B smaller than main), CrateButton 58,489 B, AlbumDetailPage 11,989 B, CratePage 2,329 B, rolldown-runtime 599 B.

Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work. The router is small and easy to follow, and moving the album-return logic from the global document click listener to subscribeBeforeNavigate is a lot cleaner. Here is what I checked and what I think needs a change.

Looks good

  • Base path: appHref and stripBasePath handle /project2, /project2/ and trailing slashes, and /project2foo is not treated as part of the base.
  • Modifier keys: Link leaves Ctrl/Cmd/Shift/Alt clicks, non-primary buttons, target, download and cross-origin links to the browser. Middle click never reaches onClick.
  • Apache fallback: this works with the existing FallbackResource /project2/index.html from #82 (docs/VM-setup.md) and the deploy check on /project2/album/1. Deep links, reloads and "open in new tab" from a card should all load on the VM. No Apache change is needed in this PR.
  • Back/forward: both the router and useSearchState now listen to the same popstate subscription, so the URL and the search state can't get out of sync.
  • Cache: mergeCursorConnection behaves the same as the two old merge functions. Updating Album:<id> keeps myCrate in sync, and evicting searchAlbums makes Discover refetch rating sort, the reviewed filter and reviewedCount when you go back. The restore effect fetches the missing pages after the eviction, so scroll restoration still works.
  • userIdentity: the try/catch and the in-memory fallback are correct, and the "storage becomes writable again" test covers the tricky case.

Request changes

  1. Focus and announcements on route change. Before this PR, every navigation was a full page load, so screen readers announced the new page. Now nothing happens: the card link you clicked unmounts, focus falls back to <body>, and there is no announcement. document.title also stays the same on every route. Please do this when the pathname changes (not when only the query changes): move focus to <main id="main">, which already has tabIndex={-1}, or to the page <h1>, and set document.title per route (for example "Album title · Crate"). Skip it on the first load so you don't steal focus. A test that checks document.activeElement after clicking an album card would cover it.
  2. Stale chunks after a deploy. The deploy deletes /var/www/html/project2 and copies in new hashed assets. A tab that stays open (more likely now that navigation doesn't reload the page) then lazy-loads an old AlbumDetailPage-<hash>.js. FallbackResource answers that with index.html as 200 text/html, so the dynamic import fails with a MIME error. There is no error boundary around the Suspense, so the whole app goes blank. A small error boundary, or lazy(() => import(...).catch(() => window.location.reload())) with a guard against reload loops, would fix it.

Non-blocking

  • The skip link resets Discover's pagination. In Chrome and Firefox, clicking <a href="#main"> fires popstate. handlePopState bumps locationKey, so visitKey changes and useAlbumSearch drops back to 20 visible results, even if the user had loaded 60. You could ignore popstate when only the hash changed, or leave location.key out of visitKey for hash-only changes. I found this by reading the code, so it's worth checking in the browser.
  • Redundant cache.modify. UPSERT_REVIEW and DELETE_REVIEW already select album { id averageRating reviewCount myReview { ... } }, and Apollo writes that into Album:<id> before update runs. So the cache.modify in updateCacheAfterReviewMutation doesn't change anything. Only the evict and gc calls are needed. It's harmless, but the comment makes it sound like it does more than it does.
  • pushState(window.history.state, ...). This copies the previous entry's state into the new entry. null (or { key }) would be clearer.

@erikhfj
Copy link
Member Author

erikhfj commented Nov 26, 2026

Thanks for the thorough review, @evenkkl! Addressed all requested changes and non-blocking notes in be93c6c:

  • Route-change focus management: App.tsx now moves focus to <main id="main"> (with { preventScroll: true }) on pathname changes while leaving initial mount, query-only changes, and hash-only changes untouched. A RouteFocusSettler inside lazy <Suspense> routes ensures focus lands on the mounted route's <main id="main"> once a lazy chunk replaces the fallback. (Per-route document.title is handled in feat: #132 a11y/theme/UX polish, #133 hero LCP & Apache headers, and #135 final docs/screenshots #140.) Added coverage in client/src/router.test.tsx.
  • Stale chunks after deploy: Added client/src/components/RouteErrorBoundary.tsx around the route <Suspense> tree. It detects dynamic-import/chunk load failures, reloads once per URL within a 30s cooldown guarded via sessionStorage (falling back safely if storage is blocked so reload loops cannot happen), and renders an accessible role="alert" fallback with a "Reload page" button if the error persists. Added unit tests in client/src/components/RouteErrorBoundary.test.tsx.
  • Skip link hash-only popstate: handlePopState in client/src/router.ts now ignores hash-only changes so clicking <a href="#main"> does not bump locationKey or reset Discover's loaded pagination. Added a unit test in client/src/router.test.tsx.
  • Redundant cache.modify: Removed the redundant cache.modify from updateCacheAfterReviewMutation in client/src/api/reviews.ts (leaving searchAlbums eviction + cache.gc()), updated the comment to reflect Apollo's automatic Album:<id> normalization, and updated client/src/api/client.test.ts to verify normalization + eviction.
  • pushState state arg: Changed window.history.pushState in client/src/router.ts to pass null instead of copying window.history.state.

Verified locally with pnpm codegen && pnpm format:check && pnpm lint && pnpm typecheck && pnpm test && pnpm build.

Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this addresses everything. Approving.

  • Focus on route change: fixed. Focus moves to <main id="main"> only when the pathname changes. For lazy routes, RouteFocusSettler moves focus to the real <main> once the Suspense fallback unmounts. AlbumDetailPage's own loading state returns a <main> at the same position, so React keeps the same DOM node and focus isn't lost a second time when the data arrives.
  • Stale chunks: fixed, and it can't get stuck in a reload loop. It reloads at most once per URL every 30 s. If sessionStorage is blocked it never reloads automatically, and the role="alert" fallback with a "Reload page" button covers the rest. Non-chunk errors now show the fallback instead of a blank page, which is a nice bonus.
  • Skip link: fixed. A popstate that only changes the hash, and a navigate() that only changes the hash, no longer bump locationKey.
  • cache.modify and pushState: both done.
  • document.title: fine to leave to #140. I checked that #140 sets it for Discover, album detail (loading/unavailable/title) and the crate.

Optional: the lazy-route focus handoff (fallback → real <main>) doesn't seem to have its own test. A test with a lazy component that resolves after a delay would lock it in.

@erikhfj erikhfj merged commit d4a07ad into main Nov 26, 2026
3 checks passed
Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add client-side routing, review Apollo cache updates, and client state resilience
2 participants