From 1e70234eaa2989a1aa190d7008167ed7b4aa883b Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Mon, 16 Nov 2026 11:45:30 +0100 Subject: [PATCH 1/7] refactor: one common page param hook, redirect invalid pages --- .../BookPagination/BookPagination.tsx | 4 +- .../selectedBook/BookReviews/BookReviews.tsx | 16 +++--- .../app/hooks/useBookSearchParams.test.tsx | 17 +------ frontend/app/hooks/useBookSearchParams.ts | 12 ++--- frontend/app/hooks/usePageParam.test.tsx | 50 +++++++++++++++++++ frontend/app/hooks/usePageParam.ts | 24 +++++++++ frontend/app/hooks/useReviews.ts | 18 ------- frontend/app/routes/books.test.tsx | 23 +++++++++ frontend/app/routes/books.tsx | 10 ++-- frontend/app/routes/profile.tsx | 25 ++++++---- 10 files changed, 136 insertions(+), 63 deletions(-) create mode 100644 frontend/app/hooks/usePageParam.test.tsx create mode 100644 frontend/app/hooks/usePageParam.ts diff --git a/frontend/app/components/BookPagination/BookPagination.tsx b/frontend/app/components/BookPagination/BookPagination.tsx index 2f552347..eb5c2287 100644 --- a/frontend/app/components/BookPagination/BookPagination.tsx +++ b/frontend/app/components/BookPagination/BookPagination.tsx @@ -8,7 +8,7 @@ import { PaginationNext, PaginationPrevious, } from "~/components/ui/Pagination"; -import { parsePageNum } from "~/hooks/useBookSearchParams"; +import { usePageParam } from "~/hooks/usePageParam"; const DISABLED_STYLE = "pointer-events-none opacity-50"; @@ -25,7 +25,7 @@ function BookPagination({ scrollTargetId, }: BookPaginationProps) { const [searchParams] = useSearchParams(); - const currentPage = parsePageNum(searchParams.get(searchParam)); + const { page: currentPage } = usePageParam(searchParam); const isFirstPage = currentPage === 1; const isLastPage = currentPage === totalPages; diff --git a/frontend/app/components/selectedBook/BookReviews/BookReviews.tsx b/frontend/app/components/selectedBook/BookReviews/BookReviews.tsx index 78fbae63..dd0cf41c 100644 --- a/frontend/app/components/selectedBook/BookReviews/BookReviews.tsx +++ b/frontend/app/components/selectedBook/BookReviews/BookReviews.tsx @@ -4,7 +4,12 @@ import { ReviewForm } from "~/components/selectedBook/ReviewForm/ReviewForm"; import { ReviewList } from "~/components/ReviewList/ReviewList"; import { Separator } from "~/components/ui/Separator"; import { Skeleton } from "~/components/ui/Skeleton"; -import { useBookReviews, useMyReview, useReviewPage } from "~/hooks/useReviews"; +import { usePageParam } from "~/hooks/usePageParam"; +import { + REVIEW_PAGE_PARAM, + useBookReviews, + useMyReview, +} from "~/hooks/useReviews"; function BookReviews({ bookId, @@ -18,11 +23,8 @@ function BookReviews({ bookId, enabled: !!session, }); - const { page, firstPageSearch } = useReviewPage(); - const { reviews, totalCount, error } = useBookReviews({ - bookId, - page: page ?? 1, - }); + const { page, isInvalid, firstPageSearch } = usePageParam(REVIEW_PAGE_PARAM); + const { reviews, totalCount, error } = useBookReviews({ bookId, page }); return (
- {page === null || (page > 1 && reviews?.length === 0) ? ( + {isInvalid || (page > 1 && reviews?.length === 0) ? ( // The page is invalid or has no reviews, e.g. after reviews were deleted ) : error ? ( diff --git a/frontend/app/hooks/useBookSearchParams.test.tsx b/frontend/app/hooks/useBookSearchParams.test.tsx index 85690d9b..7ca15392 100644 --- a/frontend/app/hooks/useBookSearchParams.test.tsx +++ b/frontend/app/hooks/useBookSearchParams.test.tsx @@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest"; import { renderHook } from "@testing-library/react"; import type { ReactNode } from "react"; import { MemoryRouter } from "react-router"; -import { parsePageNum, useBookSearchParams } from "~/hooks/useBookSearchParams"; -import { MAX_GENRES, MAX_PAGE, MAX_QUERY_LENGTH } from "~/lib/constants"; +import { useBookSearchParams } from "~/hooks/useBookSearchParams"; +import { MAX_GENRES, MAX_QUERY_LENGTH } from "~/lib/constants"; function renderWithUrl(url: string) { return renderHook(() => useBookSearchParams(), { @@ -13,19 +13,6 @@ function renderWithUrl(url: string) { }); } -describe("parsePageNum", () => { - it("falls back to page 1 for missing or invalid values", () => { - expect(parsePageNum(null)).toBe(1); - expect(parsePageNum("0")).toBe(1); - expect(parsePageNum("-3")).toBe(1); - expect(parsePageNum("abc")).toBe(1); - }); - - it("caps the page so the offset fits in a GraphQL Int", () => { - expect(parsePageNum("999999999999")).toBe(MAX_PAGE); - }); -}); - describe("useBookSearchParams", () => { it("cuts a long query from the URL", () => { const { result } = renderWithUrl(`/?q=${"a".repeat(250)}`); diff --git a/frontend/app/hooks/useBookSearchParams.ts b/frontend/app/hooks/useBookSearchParams.ts index 4c8046cf..e8233f0f 100644 --- a/frontend/app/hooks/useBookSearchParams.ts +++ b/frontend/app/hooks/useBookSearchParams.ts @@ -2,18 +2,14 @@ import { useMemo } from "react"; import { useSearchParams } from "react-router"; import type { BookFilters } from "~/api/types"; import { parseBookSort } from "~/api/bookSort"; -import { MAX_GENRES, MAX_PAGE, MAX_QUERY_LENGTH } from "~/lib/constants"; +import { usePageParam } from "~/hooks/usePageParam"; +import { MAX_GENRES, MAX_QUERY_LENGTH } from "~/lib/constants"; function parseCount(value: string | null) { const count = Number(value); return value && Number.isInteger(count) && count >= 0 ? count : undefined; } -function parsePageNum(value: string | null) { - const page = Number(value); - return Number.isInteger(page) && page >= 1 ? Math.min(page, MAX_PAGE) : 1; -} - const FILTER_KEYS = [ "genres", "language", @@ -28,7 +24,7 @@ function useBookSearchParams() { // Remove any characters above the limit if the user somehow manages to add them const query = (searchParams.get("q") ?? "").slice(0, MAX_QUERY_LENGTH); - const page = parsePageNum(searchParams.get("page")); + const { page } = usePageParam(); const sort = parseBookSort(searchParams.get("sort")); // Only update filters when searchParams change to avoid unnecessary re-renders @@ -56,4 +52,4 @@ function useBookSearchParams() { return { query, page, filters, sort, activeFiltersCount }; } -export { FILTER_KEYS, parsePageNum, useBookSearchParams }; +export { FILTER_KEYS, useBookSearchParams }; diff --git a/frontend/app/hooks/usePageParam.test.tsx b/frontend/app/hooks/usePageParam.test.tsx new file mode 100644 index 00000000..ce316c84 --- /dev/null +++ b/frontend/app/hooks/usePageParam.test.tsx @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import { renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { MemoryRouter } from "react-router"; +import { usePageParam } from "~/hooks/usePageParam"; +import { MAX_PAGE } from "~/lib/constants"; + +function renderWithUrl(url: string, param?: string) { + return renderHook(() => usePageParam(param), { + wrapper: ({ children }: { children: ReactNode }) => ( + {children} + ), + }); +} + +describe("usePageParam", () => { + it("reads the page from the URL", () => { + const { result } = renderWithUrl("/?page=3"); + + expect(result.current.page).toBe(3); + expect(result.current.isInvalid).toBe(false); + }); + + it("uses page 1 when the URL has no page", () => { + const { result } = renderWithUrl("/"); + + expect(result.current.page).toBe(1); + expect(result.current.isInvalid).toBe(false); + }); + + it.each(["0", "-3", "abc", "2.5", "", String(MAX_PAGE + 1)])( + "marks the page %s as invalid and uses page 1", + (page) => { + const { result } = renderWithUrl(`/?page=${page}`); + + expect(result.current.page).toBe(1); + expect(result.current.isInvalid).toBe(true); + }, + ); + + it("removes only its own param from the first page URL", () => { + const { result } = renderWithUrl( + "/?q=dune&page=abc&reviewPage=2", + "reviewPage", + ); + + expect(result.current.page).toBe(2); + expect(result.current.firstPageSearch).toBe("q=dune&page=abc"); + }); +}); diff --git a/frontend/app/hooks/usePageParam.ts b/frontend/app/hooks/usePageParam.ts new file mode 100644 index 00000000..144ee3d1 --- /dev/null +++ b/frontend/app/hooks/usePageParam.ts @@ -0,0 +1,24 @@ +import { useSearchParams } from "react-router"; +import { MAX_PAGE } from "~/lib/constants"; + +/** + * Reads a page number from the URL. An invalid page, like "0", "abc" or a page + * so large the offset no longer fits in a GraphQL Int, counts as page 1 and sets + * isInvalid. The page can then redirect to firstPageSearch instead + */ +function usePageParam(param = "page") { + const [searchParams] = useSearchParams(); + const page = Number(searchParams.get(param) ?? "1"); + const isInvalid = !Number.isInteger(page) || page < 1 || page > MAX_PAGE; + + const firstPageParams = new URLSearchParams(searchParams); + firstPageParams.delete(param); + + return { + page: isInvalid ? 1 : page, + isInvalid, + firstPageSearch: firstPageParams.toString(), + }; +} + +export { usePageParam }; diff --git a/frontend/app/hooks/useReviews.ts b/frontend/app/hooks/useReviews.ts index 0a0603e8..187d6b4f 100644 --- a/frontend/app/hooks/useReviews.ts +++ b/frontend/app/hooks/useReviews.ts @@ -102,23 +102,6 @@ const DELETE_REVIEW: TypedDocumentNode< } `; -/** - * Reads the page of reviews from the URL. The page is null if the URL has an - * invalid page, like "0" or "abc", so the caller can send the user to the first page - */ -function useReviewPage() { - const [searchParams] = useSearchParams(); - const page = Number(searchParams.get(REVIEW_PAGE_PARAM) ?? "1"); - - const firstPageParams = new URLSearchParams(searchParams); - firstPageParams.delete(REVIEW_PAGE_PARAM); - - return { - page: Number.isInteger(page) && page >= 1 ? page : null, - firstPageSearch: firstPageParams.toString(), - }; -} - function useBookReviews({ bookId, page }: { bookId: string; page: number }) { const { data, previousData, error } = useQuery(BOOK_REVIEWS, { variables: { @@ -237,7 +220,6 @@ function useReviewMutations({ bookId }: { bookId: string }) { } export { - useReviewPage, useBookReviews, useMyReview, useMyReviews, diff --git a/frontend/app/routes/books.test.tsx b/frontend/app/routes/books.test.tsx index 69fecc10..9f217f73 100644 --- a/frontend/app/routes/books.test.tsx +++ b/frontend/app/routes/books.test.tsx @@ -136,6 +136,29 @@ describe("BooksPage", () => { ).toHaveTextContent("2"); }); + it.each(["0", "abc", "999999999999"])( + "goes to the first page with the same search when the page in the URL is %s", + async (page) => { + renderRoutes(routes, { + initialEntries: [`/books?q=blade&page=${page}`], + mocks: [ + searchBooksMock( + { query: "blade", limit: 12, offset: 0 }, + undefined, + 15, + ), + ], + }); + + expect(await screen.findByText("15 results")).toBeInTheDocument(); + expect( + within( + screen.getByRole("navigation", { name: "pagination" }), + ).getByRole("link", { current: "page" }), + ).toHaveTextContent("1"); + }, + ); + it("tells the user when no books match the search", async () => { renderRoutes(routes, { initialEntries: ["/books?q=zzzz"], diff --git a/frontend/app/routes/books.tsx b/frontend/app/routes/books.tsx index c0d59fb3..131d9068 100644 --- a/frontend/app/routes/books.tsx +++ b/frontend/app/routes/books.tsx @@ -6,6 +6,7 @@ import { SortSelect } from "~/components/books/SortSelect/SortSelect"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; import { useBookSearchParams } from "~/hooks/useBookSearchParams"; import { useSuggestedBooks } from "~/hooks/useSuggestedBooks"; +import { usePageParam } from "~/hooks/usePageParam"; import { Navigate, useSearchParams } from "react-router"; import { useDataIsDelayed } from "~/hooks/useDataIsDelayed"; import type { ReactNode } from "react"; @@ -98,6 +99,7 @@ export default function BooksPage() { const [searchParams] = useSearchParams(); const { query, page, filters, sort, activeFiltersCount } = useBookSearchParams(); + const { isInvalid: isInvalidPage, firstPageSearch } = usePageParam(); const { books, totalCount, loading, error } = useSearchBooks({ filters, @@ -130,9 +132,11 @@ export default function BooksPage() { // Redirect to page 1, keeping the search query, filters and sort function redirectToFirstPage() { - const firstPageParams = new URLSearchParams(searchParams); - firstPageParams.delete("page"); - return ; + return ; + } + + if (isInvalidPage) { + return redirectToFirstPage(); } // Later loads keep showing the previous books until the new ones arrive, diff --git a/frontend/app/routes/profile.tsx b/frontend/app/routes/profile.tsx index d6a78952..e9f4ec96 100644 --- a/frontend/app/routes/profile.tsx +++ b/frontend/app/routes/profile.tsx @@ -1,7 +1,7 @@ -import { Link, Navigate, useSearchParams } from "react-router"; +import { Link, Navigate } from "react-router"; import { authClient } from "~/api/auth"; import { useFavoriteBooks } from "~/hooks/useFavoriteBooks"; -import { parsePageNum } from "~/hooks/useBookSearchParams"; +import { usePageParam } from "~/hooks/usePageParam"; import { BookCard, BookCardSkeleton } from "~/components/BookCard/BookCard"; import { BookPagination } from "~/components/BookPagination/BookPagination"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; @@ -18,7 +18,7 @@ import { CardTitle, } from "~/components/ui/Card"; import { Skeleton } from "~/components/ui/Skeleton"; -import { useMyReviews, useReviewPage } from "~/hooks/useReviews"; +import { REVIEW_PAGE_PARAM, useMyReviews } from "~/hooks/useReviews"; import { FAVORITE_BOOKS_PAGE_LIMIT } from "~/lib/constants"; import { Separator } from "~/components/ui/Separator"; @@ -28,19 +28,21 @@ export function meta() { export default function ProfilePage() { const { data: session, isPending } = authClient.useSession(); - const [searchParams] = useSearchParams(); - const page = parsePageNum(searchParams.get("page")); + const { page, isInvalid: isInvalidPage } = usePageParam(); const { books, totalCount, topGenres, loading, error } = useFavoriteBooks({ enabled: !!session, page, }); - const { page: reviewPage, firstPageSearch: firstReviewPageSearch } = - useReviewPage(); + const { + page: reviewPage, + isInvalid: isInvalidReviewPage, + firstPageSearch: firstReviewPageSearch, + } = usePageParam(REVIEW_PAGE_PARAM); const myReviews = useMyReviews({ enabled: !!session, - page: reviewPage ?? 1, + page: reviewPage, }); const totalPages = Math.ceil(totalCount / FAVORITE_BOOKS_PAGE_LIMIT); @@ -58,12 +60,15 @@ export default function ProfilePage() { return ; } - if ((!books || books.length === 0) && !loading && page > 1) { + if ( + isInvalidPage || + ((!books || books.length === 0) && !loading && page > 1) + ) { return ; } if ( - reviewPage === null || + isInvalidReviewPage || (reviewPage > 1 && myReviews.reviews?.length === 0) ) { // The page is invalid or has no reviews, e.g. after reviews were deleted From bb61cdc36885ee03e713767336b090987ff5bb72 Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Mon, 16 Nov 2026 11:51:22 +0100 Subject: [PATCH 2/7] fix: keep search params on invalid page on favorites redirect --- frontend/app/routes/profile.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/frontend/app/routes/profile.tsx b/frontend/app/routes/profile.tsx index e9f4ec96..91796936 100644 --- a/frontend/app/routes/profile.tsx +++ b/frontend/app/routes/profile.tsx @@ -28,7 +28,7 @@ export function meta() { export default function ProfilePage() { const { data: session, isPending } = authClient.useSession(); - const { page, isInvalid: isInvalidPage } = usePageParam(); + const { page, isInvalid: isInvalidPage, firstPageSearch } = usePageParam(); const { books, totalCount, topGenres, loading, error } = useFavoriteBooks({ enabled: !!session, @@ -60,11 +60,10 @@ export default function ProfilePage() { return ; } - if ( - isInvalidPage || - ((!books || books.length === 0) && !loading && page > 1) - ) { - return ; + // The page is invalid or has no favorites, e.g. after favorites were removed. + // A failed request has no books, so it shows the error instead + if (isInvalidPage || (page > 1 && !loading && books?.length === 0)) { + return ; } if ( From 1301558b8aec083c978df8c0cd3ec50455615616 Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Mon, 16 Nov 2026 11:51:28 +0100 Subject: [PATCH 3/7] test: add tests for profile page --- frontend/app/routes/profile.test.tsx | 93 ++++++++++++++++++++++++++++ frontend/app/test/session.ts | 7 ++- 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 frontend/app/routes/profile.test.tsx diff --git a/frontend/app/routes/profile.test.tsx b/frontend/app/routes/profile.test.tsx new file mode 100644 index 00000000..20cd7c52 --- /dev/null +++ b/frontend/app/routes/profile.test.tsx @@ -0,0 +1,93 @@ +import { describe, expect, it, vi } from "vitest"; +import { screen } from "@testing-library/react"; +import type { MockLink } from "@apollo/client/testing"; +import ProfilePage from "~/routes/profile"; +import { FAVORITE_BOOKS } from "~/hooks/useFavoriteBooks"; +import { MY_REVIEWS } from "~/hooks/useReviews"; +import { renderRoutes } from "~/test/renderRoutes"; +import { loggedIn } from "~/test/session"; + +vi.mock("~/api/auth", () => ({ + authClient: { useSession: vi.fn(() => loggedIn) }, +})); + +const routes = [{ path: "/profile", Component: ProfilePage }]; + +// No favorite books, so the page sends no requests for the book cards +function favoriteBooksMock(offset: number): MockLink.MockedResponse { + return { + request: { query: FAVORITE_BOOKS, variables: { limit: 3, offset } }, + result: { + data: { + favoriteBooks: { + __typename: "BookSearchResult", + totalCount: 0, + books: [], + }, + favoriteGenres: [], + }, + }, + }; +} + +function myReviewsMock(offset: number): MockLink.MockedResponse { + return { + request: { query: MY_REVIEWS, variables: { limit: 10, offset } }, + result: { + data: { + myReviews: { + __typename: "ReviewSearchResult", + totalCount: 11, + reviews: [ + { + __typename: "Review", + id: 1, + rating: 5, + comment: "Very cool!", + createdAt: "2026-11-01T12:00:00.000Z", + book: { __typename: "Book", id: 1, title: "The Blade Itself" }, + }, + ], + }, + }, + }, + maxUsageCount: 2, + }; +} + +describe("ProfilePage", () => { + it("goes to the first page of favorites and keeps the page of reviews", async () => { + renderRoutes(routes, { + initialEntries: ["/profile?page=3&reviewPage=2"], + mocks: [favoriteBooksMock(6), favoriteBooksMock(0), myReviewsMock(10)], + }); + + expect( + await screen.findByText(/You have no favorite books yet/), + ).toBeInTheDocument(); + expect(screen.getByText("Very cool!")).toBeInTheDocument(); + }); + + it("shows an error instead of going to the first page when favorites fail to load", async () => { + renderRoutes(routes, { + initialEntries: ["/profile?page=2"], + mocks: [ + { + request: { + query: FAVORITE_BOOKS, + variables: { limit: 3, offset: 3 }, + }, + error: new Error("Network error"), + }, + favoriteBooksMock(0), + myReviewsMock(0), + ], + }); + + expect( + await screen.findByText( + "Could not load your favorite books. Please try again later.", + ), + ).toBeInTheDocument(); + }); +}); diff --git a/frontend/app/test/session.ts b/frontend/app/test/session.ts index c3444907..28046224 100644 --- a/frontend/app/test/session.ts +++ b/frontend/app/test/session.ts @@ -13,7 +13,12 @@ const loggedOut = { const loggedIn = { data: { - user: { id: "user-1", name: "Test User", email: "test@example.com" }, + user: { + id: "user-1", + name: "Test User", + email: "test@example.com", + createdAt: new Date("2026-01-01"), + }, session: { id: "session-1", userId: "user-1" }, }, isPending: false, From 23ba94de27dbf631d0175e6eced8878ea6afb725 Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Mon, 16 Nov 2026 11:54:46 +0100 Subject: [PATCH 4/7] refractor: rename BookPagination to ItemPagination --- frontend/README.md | 2 +- .../ItemPagination.test.tsx} | 8 ++++---- .../ItemPagination.tsx} | 8 ++++---- frontend/app/components/ReviewList/ReviewList.tsx | 4 ++-- frontend/app/routes/books.tsx | 6 +++--- frontend/app/routes/profile.tsx | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) rename frontend/app/components/{BookPagination/BookPagination.test.tsx => ItemPagination/ItemPagination.test.tsx} (94%) rename frontend/app/components/{BookPagination/BookPagination.tsx => ItemPagination/ItemPagination.tsx} (97%) diff --git a/frontend/README.md b/frontend/README.md index b2e3df97..53a5f523 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -88,7 +88,7 @@ We test where there is logic, state or several parts working together. Static markup (like `Header` and `Footer`) is not tested: such tests break on every intended change without catching real bugs. -- **Component tests** for `BookCard`, `BookPagination`, `FavoriteButton`, +- **Component tests** for `BookCard`, `ItemPagination`, `FavoriteButton`, `FilterBooksSection` and `SearchBar`: rendering based on props, user interaction (clicks, typing), keeping search and filters in sync with the URL, and paging. diff --git a/frontend/app/components/BookPagination/BookPagination.test.tsx b/frontend/app/components/ItemPagination/ItemPagination.test.tsx similarity index 94% rename from frontend/app/components/BookPagination/BookPagination.test.tsx rename to frontend/app/components/ItemPagination/ItemPagination.test.tsx index 0ef80d02..6f553373 100644 --- a/frontend/app/components/BookPagination/BookPagination.test.tsx +++ b/frontend/app/components/ItemPagination/ItemPagination.test.tsx @@ -1,14 +1,14 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { BookPagination } from "~/components/BookPagination/BookPagination"; +import { ItemPagination } from "~/components/ItemPagination/ItemPagination"; import { createRoutesStub } from "react-router"; // Pagination reads and writes the current page in the "page" search param. const Stub = createRoutesStub([ { path: "/", - Component: () => , + Component: () => , }, ]); @@ -23,7 +23,7 @@ function prefersReducedMotion(reduce: boolean) { const currentPage = () => screen.getByRole("link", { current: "page" }).textContent; -describe("BookPagination", () => { +describe("ItemPagination", () => { afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); @@ -101,7 +101,7 @@ describe("BookPagination", () => { { path: "/", Component: () => ( - + ), }, ]); diff --git a/frontend/app/components/BookPagination/BookPagination.tsx b/frontend/app/components/ItemPagination/ItemPagination.tsx similarity index 97% rename from frontend/app/components/BookPagination/BookPagination.tsx rename to frontend/app/components/ItemPagination/ItemPagination.tsx index eb5c2287..0aae6431 100644 --- a/frontend/app/components/BookPagination/BookPagination.tsx +++ b/frontend/app/components/ItemPagination/ItemPagination.tsx @@ -12,18 +12,18 @@ import { usePageParam } from "~/hooks/usePageParam"; const DISABLED_STYLE = "pointer-events-none opacity-50"; -interface BookPaginationProps { +interface ItemPaginationProps { totalPages: number; searchParam?: string; // id of the element to scroll to when changing page. Scrolls to the top of the page by default scrollTargetId?: string; } -function BookPagination({ +function ItemPagination({ totalPages, searchParam = "page", scrollTargetId, -}: BookPaginationProps) { +}: ItemPaginationProps) { const [searchParams] = useSearchParams(); const { page: currentPage } = usePageParam(searchParam); @@ -125,4 +125,4 @@ function BookPagination({ ); } -export { BookPagination }; +export { ItemPagination }; diff --git a/frontend/app/components/ReviewList/ReviewList.tsx b/frontend/app/components/ReviewList/ReviewList.tsx index 6e18b6a9..96180b4b 100644 --- a/frontend/app/components/ReviewList/ReviewList.tsx +++ b/frontend/app/components/ReviewList/ReviewList.tsx @@ -1,5 +1,5 @@ import { Link } from "react-router"; -import { BookPagination } from "~/components/BookPagination/BookPagination"; +import { ItemPagination } from "~/components/ItemPagination/ItemPagination"; import { StarRating } from "~/components/StarRating/StarRating"; import { REVIEW_PAGE_LIMIT, REVIEW_PAGE_PARAM } from "~/hooks/useReviews"; @@ -60,7 +60,7 @@ function ReviewList({ reviews, totalCount, headingId }: ReviewListProps) { ))} {totalPages > 1 && ( - -
@@ -225,7 +225,7 @@ export default function BooksPage() { - + ); } diff --git a/frontend/app/routes/profile.tsx b/frontend/app/routes/profile.tsx index 91796936..02dd4ae2 100644 --- a/frontend/app/routes/profile.tsx +++ b/frontend/app/routes/profile.tsx @@ -3,7 +3,7 @@ import { authClient } from "~/api/auth"; import { useFavoriteBooks } from "~/hooks/useFavoriteBooks"; import { usePageParam } from "~/hooks/usePageParam"; import { BookCard, BookCardSkeleton } from "~/components/BookCard/BookCard"; -import { BookPagination } from "~/components/BookPagination/BookPagination"; +import { ItemPagination } from "~/components/ItemPagination/ItemPagination"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; import { ReviewList } from "~/components/ReviewList/ReviewList"; import { Avatar, AvatarFallback } from "~/components/ui/Avatar"; @@ -201,7 +201,7 @@ export default function ProfilePage() { ))} )} - {totalPages > 1 && } + {totalPages > 1 && }
Date: Mon, 16 Nov 2026 12:03:11 +0100 Subject: [PATCH 5/7] fix: show selected book also when book list is missing --- frontend/app/routes/book/selectedBook.test.tsx | 16 ++++++++++++++++ frontend/app/routes/book/selectedBook.tsx | 18 +++++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/frontend/app/routes/book/selectedBook.test.tsx b/frontend/app/routes/book/selectedBook.test.tsx index d83c0f1b..0b143993 100644 --- a/frontend/app/routes/book/selectedBook.test.tsx +++ b/frontend/app/routes/book/selectedBook.test.tsx @@ -43,6 +43,22 @@ describe("SelectedBookPage", () => { ).toBeInTheDocument(); }); + // E.g. a shared link to a book from someone's favorites + it("shows a book from the favorites when logged out, without browsing", async () => { + renderRoutes(routes, { + initialEntries: ["/book/1?origin=favorites"], + mocks: [bookMock(1, apiBook)], + }); + + expect(await screen.findByText(/Logen Ninefingers/)).toBeInTheDocument(); + expect( + screen.getByRole("link", { name: "Go to previous book" }), + ).toHaveAttribute("aria-disabled", "true"); + expect( + screen.getByRole("link", { name: "Go to next book" }), + ).toHaveAttribute("aria-disabled", "true"); + }); + it("browses to the next book in the search results", async () => { const user = userEvent.setup(); renderRoutes(routes, { diff --git a/frontend/app/routes/book/selectedBook.tsx b/frontend/app/routes/book/selectedBook.tsx index 9f603d03..ee8cd45b 100644 --- a/frontend/app/routes/book/selectedBook.tsx +++ b/frontend/app/routes/book/selectedBook.tsx @@ -1,4 +1,5 @@ import type { Route } from "./+types/selectedBook"; +import { authClient } from "~/api/auth"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; import { BookCover } from "~/components/BookCover/BookCover"; import { FavoriteButton } from "~/components/FavoriteButton/FavoriteButton"; @@ -29,6 +30,7 @@ const DISABLED_STYLE = "pointer-events-none opacity-50"; export default function SelectedBookPage({ params }: Route.ComponentProps) { const [searchParams] = useSearchParams(); const { query, page, filters, sort } = useBookSearchParams(); + const { data: session } = authClient.useSession(); const origin = searchParams.get("origin"); const { book, loading, error } = useBook({ id: params.bookId }); @@ -46,7 +48,8 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { const { books: favoriteBooks } = useFavoriteBooks({ page, - enabled: origin === "favorites", + // Only logged in users have favorites + enabled: origin === "favorites" && !!session, }); const { books: suggestedBooks } = useSuggestedBooks({ @@ -75,7 +78,7 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { ); } - if (error || !book || !books) { + if (error || !book) { return (
{/* Uses instead of meta() to allow the document title to be defined dynamically in the route. */} @@ -89,11 +92,12 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { const paramsWithoutOrigin = new URLSearchParams(searchParams); paramsWithoutOrigin.delete("origin"); - // index is -1 if the book is not on the current search page; - // then both browse buttons are disabled. - const index = books.findIndex((b) => b.id === book.id); - const previousBook = index > 0 ? books[index - 1] : undefined; - const nextBook = index >= 0 ? books[index + 1] : undefined; + // index is -1 if the list of books is missing, e.g. while it loads or when + // logged out, or if the book is not on the current page. Then both browse + // buttons are disabled + const index = books?.findIndex((b) => b.id === book.id) ?? -1; + const previousBook = index > 0 ? books?.[index - 1] : undefined; + const nextBook = index >= 0 ? books?.[index + 1] : undefined; return ( <main> From c4d99fd4c035d5281fc807616f79871f3d17a572 Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski <martakam@stud.ntnu.no> Date: Mon, 16 Nov 2026 12:35:02 +0100 Subject: [PATCH 6/7] fix: show loading for suggestions instead of error --- frontend/app/hooks/useSuggestedBooks.ts | 19 +++++++--------- frontend/app/routes/books.test.tsx | 29 ++++++++++++++++++++++++- frontend/app/routes/books.tsx | 6 +++-- 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/frontend/app/hooks/useSuggestedBooks.ts b/frontend/app/hooks/useSuggestedBooks.ts index 54361736..c9e0717f 100644 --- a/frontend/app/hooks/useSuggestedBooks.ts +++ b/frontend/app/hooks/useSuggestedBooks.ts @@ -52,17 +52,14 @@ function useSuggestedBooks({ enabled: enabled && !similar.loading && !hasSimilar, }); - return hasSimilar - ? { - books: similar.books, - totalCount: similar.totalCount, - similarTitles: true, - } - : { - books: topRated.books, - totalCount: topRated.totalCount, - similarTitles: false, - }; + const result = hasSimilar ? similar : topRated; + + return { + books: result.books, + totalCount: result.totalCount, + similarTitles: hasSimilar, + loading: enabled && !result.books && !result.error, + }; } export { useSuggestedBooks }; diff --git a/frontend/app/routes/books.test.tsx b/frontend/app/routes/books.test.tsx index 9f217f73..c936da05 100644 --- a/frontend/app/routes/books.test.tsx +++ b/frontend/app/routes/books.test.tsx @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { screen, waitFor, within } from "@testing-library/react"; +import { act, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import BooksPage from "~/routes/books"; import SelectedBookPage from "~/routes/book/selectedBook"; @@ -213,6 +213,33 @@ describe("BooksPage", () => { expect(await findBookCards()).toHaveLength(3); }); + it("shows a loading state instead of no results while the suggestions load", async () => { + renderRoutes(routes, { + initialEntries: ["/books?q=blade+itslef"], + mocks: [ + searchBooksMock({ query: "blade itslef", limit: 12, offset: 0 }, []), + { + ...searchBooksMock({ + query: "blade itslef", + fuzzy: true, + limit: 12, + offset: 0, + }), + delay: 500, + }, + ], + }); + + // Let the search without results arrive, while the suggestions still load + await act(() => new Promise((resolve) => setTimeout(resolve, 100))); + + expect(screen.getByText("Loading books...")).toBeInTheDocument(); + expect( + screen.queryByText("No books found for this search"), + ).not.toBeInTheDocument(); + expect(await findBookCards()).toHaveLength(3); + }); + it("pages and sorts the similar titles", async () => { renderRoutes(routes, { initialEntries: ["/books?q=blade+itslef&sort=rating_desc&page=2"], diff --git a/frontend/app/routes/books.tsx b/frontend/app/routes/books.tsx index 939d4bbb..d3331bf0 100644 --- a/frontend/app/routes/books.tsx +++ b/frontend/app/routes/books.tsx @@ -117,6 +117,7 @@ export default function BooksPage() { books: suggestions, totalCount: suggestionCount, similarTitles, + loading: suggestionsLoading, } = useSuggestedBooks({ query, filters, @@ -140,8 +141,9 @@ export default function BooksPage() { } // Later loads keep showing the previous books until the new ones arrive, - // unless it takes a while - if ((loading && !books) || slowLoading) { + // unless it takes a while. Suggestions only load after a search without + // results, so there are no previous books to keep showing while they load + if ((loading && !books) || slowLoading || suggestionsLoading) { return ( <BooksLayout> <SortSelect /> From 6eba262f8737ccaa57a40e956da6f697fdc4cc5d Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski <martakam@stud.ntnu.no> Date: Mon, 16 Nov 2026 12:36:41 +0100 Subject: [PATCH 7/7] test: fix flaky profile test --- frontend/app/routes/profile.test.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/app/routes/profile.test.tsx b/frontend/app/routes/profile.test.tsx index 20cd7c52..465a3365 100644 --- a/frontend/app/routes/profile.test.tsx +++ b/frontend/app/routes/profile.test.tsx @@ -13,7 +13,9 @@ vi.mock("~/api/auth", () => ({ const routes = [{ path: "/profile", Component: ProfilePage }]; -// No favorite books, so the page sends no requests for the book cards +// No favorite books, so the page sends no requests for the book cards. +// While a redirect is in progress, the page can render with the old and the +// new page more than once, and each render refetches, so the mock can be reused function favoriteBooksMock(offset: number): MockLink.MockedResponse { return { request: { query: FAVORITE_BOOKS, variables: { limit: 3, offset } }, @@ -27,6 +29,7 @@ function favoriteBooksMock(offset: number): MockLink.MockedResponse { favoriteGenres: [], }, }, + maxUsageCount: Number.POSITIVE_INFINITY, }; }