Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions client/src/hooks/searchReturnState.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';

import {
clearSearchReturnState,
readSearchReturnState,
saveSearchReturnState,
} from './searchReturnState.js';

beforeEach(() => window.sessionStorage.clear());
afterEach(() => window.sessionStorage.clear());

describe('search return state', () => {
it('restores the loaded result count and scroll only for the matching URL', () => {
const state = { url: '/project2/?q=the', visibleCount: 40, scrollY: 24739 };
saveSearchReturnState(state);

expect(readSearchReturnState(state.url)).toEqual(state);
expect(readSearchReturnState('/project2/?q=abbey')).toBeNull();
});

it('ignores malformed or unsafe state', () => {
window.sessionStorage.setItem('crate.search-return-state', '{broken');
expect(readSearchReturnState('/project2/')).toBeNull();

window.sessionStorage.setItem(
'crate.search-return-state',
JSON.stringify({ url: '/project2/', visibleCount: -1, scrollY: -5 }),
);
expect(readSearchReturnState('/project2/')).toBeNull();
});

it('clears the saved state after it is restored', () => {
saveSearchReturnState({ url: '/project2/', visibleCount: 20, scrollY: 800 });
clearSearchReturnState();
expect(readSearchReturnState('/project2/')).toBeNull();
});
});
56 changes: 56 additions & 0 deletions client/src/hooks/searchReturnState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const STORAGE_KEY = 'crate.search-return-state';

export interface SearchReturnState {
url: string;
visibleCount: number;
scrollY: number;
}

export function saveSearchReturnState(state: SearchReturnState): void {
try {
window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch {
// Search navigation still works if session storage is unavailable.
}
}

export function readSearchReturnState(url: string): SearchReturnState | null {
try {
const stored = window.sessionStorage.getItem(STORAGE_KEY);
if (!stored) return null;

const state: unknown = JSON.parse(stored);
if (
typeof state !== 'object' ||
state === null ||
!('url' in state) ||
state.url !== url ||
!('visibleCount' in state) ||
typeof state.visibleCount !== 'number' ||
!Number.isInteger(state.visibleCount) ||
state.visibleCount < 1 ||
!('scrollY' in state) ||
typeof state.scrollY !== 'number' ||
!Number.isFinite(state.scrollY) ||
state.scrollY < 0
) {
return null;
}

return {
url,
visibleCount: state.visibleCount,
scrollY: state.scrollY,
};
} catch {
return null;
}
}

export function clearSearchReturnState(): void {
try {
window.sessionStorage.removeItem(STORAGE_KEY);
} catch {
// Search navigation still works if session storage is unavailable.
}
}
88 changes: 88 additions & 0 deletions client/src/hooks/useAlbumSearch.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { MockedProvider } from '@apollo/client/testing/react';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { expect, it, vi } from 'vitest';

import { cache } from '../api/client.js';
import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from '../api/searchAlbums.js';
import { useAlbumSearch } from './useAlbumSearch.js';
import { clearSearchReturnState, saveSearchReturnState } from './searchReturnState.js';

const albums = Array.from({ length: 40 }, (_, index) => ({
__typename: 'Album' as const,
id: String(index + 1),
title: `Album ${index + 1}`,
releaseYear: 2000,
musicBrainzReleaseGroupId: null,
artists: [{ __typename: 'Artist' as const, id: 'artist-1', name: 'Test Artist' }],
genres: [],
averageRating: 0,
reviewCount: 0,
isInCrate: false,
}));

function albumPage(start: number, end: number, hasNextPage: boolean) {
const pageAlbums = albums.slice(start, end);
return {
data: {
searchAlbums: {
edges: pageAlbums.map((node) => ({ cursor: `cursor-${node.id}`, node })),
...(start === 0
? {
totalCount: albums.length,
genreFacets: [],
decadeFacets: [],
countryFacets: [],
reviewedCount: 0,
}
: {}),
pageInfo: {
hasNextPage,
endCursor: pageAlbums.at(-1) ? `cursor-${pageAlbums.at(-1)!.id}` : null,
},
},
},
};
}

it('reloads the previously visible pages before restoring scroll position', async () => {
const url = '/project2/?q=the';
const scrollTo = vi.fn();
window.scrollTo = scrollTo;
window.history.replaceState({}, '', url);
saveSearchReturnState({ url, visibleCount: 40, scrollY: 24739 });

const mocks = [
{
request: {
query: SEARCH_ALBUMS,
variables: { input: { query: 'the', sort: 'RELEVANCE' }, first: 20, after: null },
},
result: albumPage(0, 20, true),
},
{
request: {
query: SEARCH_ALBUMS_PAGE,
variables: {
input: { query: 'the', sort: 'RELEVANCE' },
first: 20,
after: 'cursor-20',
},
},
result: albumPage(20, 40, false),
},
];
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks} cache={cache.restore({})}>
{children}
</MockedProvider>
);

const { result, unmount } = renderHook(() => useAlbumSearch(), { wrapper });
await waitFor(() => expect(result.current.albums).toHaveLength(40));
await waitFor(() => expect(scrollTo).toHaveBeenCalledWith(0, 24739));
expect(result.current.hasNextPage).toBe(false);

unmount();
act(() => clearSearchReturnState());
});
99 changes: 98 additions & 1 deletion client/src/hooks/useAlbumSearch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQuery } from '@apollo/client/react';
import { NetworkStatus } from '@apollo/client';

Expand All @@ -7,6 +7,11 @@ import {
SEARCH_ALBUMS_PAGE,
type AlbumSearchInput,
} from '../api/searchAlbums.js';
import {
clearSearchReturnState,
readSearchReturnState,
saveSearchReturnState,
} from './searchReturnState.js';
import { useSearchState } from './useSearchState.js';

const PAGE_SIZE = 20;
Expand All @@ -24,6 +29,10 @@ export function useAlbumSearch() {
clearFilters,
resetSearch,
} = useSearchState();
const [savedReturnState] = useState(() =>
readSearchReturnState(`${window.location.pathname}${window.location.search}`),
);
const returnState = useRef(savedReturnState);
const query = state.q;
const hasQuery = query.length > 0;
const retryInFlight = useRef(false);
Expand Down Expand Up @@ -192,6 +201,94 @@ export function useAlbumSearch() {
// Facets come from the last answer while the next one loads, so the filter
// panel does not collapse and lose keyboard focus on every click.
const facets = (data ?? previousData)?.searchAlbums;
const visibleAlbumCount = Math.min(pagination.visibleCount, edges.length);

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<HTMLAnchorElement>('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;
}

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]);

useEffect(() => {
const saved = returnState.current;
if (
!saved ||
!data ||
loading ||
pagination.key !== key ||
pagination.loadingMore ||
pagination.pageError
) {
return;
}

if (edges.length < saved.visibleCount && pageInfo?.hasNextPage) {
loadMore();
return;
}

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,
);
window.requestAnimationFrame(() => window.scrollTo(0, saved.scrollY));
}, [
data,
loading,
pagination.key,
pagination.loadingMore,
pagination.pageError,
key,
edges.length,
pageInfo?.hasNextPage,
loadMore,
]);

return {
query,
Expand Down
1 change: 1 addition & 0 deletions docs/AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ the part that matters most.
| 2026-11-22 | evenkkl | Claude | #96, skip count and facet queries on Load more: Claude made the search aggregates lazy `AlbumConnection` field resolvers, added a `SearchAlbumsPage` query for Load more, kept page one's count and facets in the Apollo merge, and added server and client tests. Verified with lint, typecheck, the test suites and the PostgreSQL tests on PGlite. |
| 2026-11-22 | erikhfj | Antigravity | #117, stabilized `ReviewForm.test.tsx`: traced the intermittent CI failure (run `88055`) to `findByRole('status')` resolving via `MutationObserver` before React's passive `useEffect` focused `statusRef`, and wrapped the status focus assertions in `waitFor`. Verified with 10 consecutive test runs plus `pnpm format:check && pnpm lint && pnpm typecheck && pnpm test`. |
| 2026-11-22 | erikhfj | Antigravity | #107, documented the team's AI task delegation, verification, and review workflow in `docs/AI-USAGE.md`, reflecting actual practices across all four contributors and complementing #97's prompt-context section. Verified with `pnpm format:check && pnpm lint && pnpm typecheck && pnpm test`. |
| 2026-11-23 | robertky | Codex (ChatGPT) | #121: Preserved the visible search page count and scroll position when opening an album, then restored the saved result pages on return. Added state and pagination regression tests. |

## Task delegation and verification workflow

Expand Down
24 changes: 24 additions & 0 deletions e2e/tests/search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,30 @@ test('search is case-insensitive', async ({ page }) => {
await expect(resultTitles(page)).toHaveText(upper);
});

test('browser back restores the previous search and scroll position', async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 400 });
await page.goto('./');
await search(page, 'beatles');
await expect(
page.getByRole('status').filter({ hasText: 'Showing 2 of 2' }),
).toBeVisible();

const results = page.getByRole('region', { name: 'Search results' });
const lastResult = results.getByRole('link').last();
await lastResult.scrollIntoViewIfNeeded();
const savedScrollY = await page.evaluate(() => window.scrollY);
const albumTitle = (await lastResult.innerText()).trim();
await lastResult.click();
await expect(page.getByRole('heading', { level: 1, name: albumTitle })).toBeVisible();

await page.goBack();
await expect(page).toHaveURL(/[?&]q=beatles/);
await expect(results.getByRole('link')).toHaveCount(2);
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(savedScrollY);
});

test('keyboard only: skip link, search and open a result', async ({ page }) => {
await page.goto('./');

Expand Down