diff --git a/frontend/README.md b/frontend/README.md index b2e3df9..53a5f52 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 0ef80d0..6f55337 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 94% rename from frontend/app/components/BookPagination/BookPagination.tsx rename to frontend/app/components/ItemPagination/ItemPagination.tsx index 2f55234..0aae643 100644 --- a/frontend/app/components/BookPagination/BookPagination.tsx +++ b/frontend/app/components/ItemPagination/ItemPagination.tsx @@ -8,24 +8,24 @@ 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"; -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 currentPage = parsePageNum(searchParams.get(searchParam)); + const { page: currentPage } = usePageParam(searchParam); const isFirstPage = currentPage === 1; const isLastPage = currentPage === totalPages; @@ -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 56717b0..3baa497 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"; @@ -62,7 +62,7 @@ function ReviewList({ reviews, totalCount, headingId }: ReviewListProps) { ))} {totalPages > 1 && ( - - {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 85690d9..7ca1539 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 4c8046c..e8233f0 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 0000000..ce316c8 --- /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 0000000..144ee3d --- /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 0a0603e..187d6b4 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/hooks/useSuggestedBooks.ts b/frontend/app/hooks/useSuggestedBooks.ts index 5436173..c9e0717 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/book/selectedBook.test.tsx b/frontend/app/routes/book/selectedBook.test.tsx index d83c0f1..0b14399 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 9f603d0..ee8cd45 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> diff --git a/frontend/app/routes/books.test.tsx b/frontend/app/routes/books.test.tsx index 69fecc1..c936da0 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"; @@ -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"], @@ -190,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 8cc5cfb..0074ee9 100644 --- a/frontend/app/routes/books.tsx +++ b/frontend/app/routes/books.tsx @@ -1,4 +1,4 @@ -import { BookPagination } from "~/components/BookPagination/BookPagination"; +import { ItemPagination } from "~/components/ItemPagination/ItemPagination"; import { useSearchBooks, type SearchBook } from "~/hooks/useSearchBooks"; import { SearchBar } from "~/components/books/SearchBar/SearchBar"; import { BookCard, BookCardSkeleton } from "~/components/BookCard/BookCard"; @@ -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"; @@ -99,6 +100,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, @@ -116,6 +118,7 @@ export default function BooksPage() { books: suggestions, totalCount: suggestionCount, similarTitles, + loading: suggestionsLoading, } = useSuggestedBooks({ query, filters, @@ -131,14 +134,17 @@ 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 <Navigate to={{ search: firstPageParams.toString() }} replace />; + return <Navigate to={{ search: firstPageSearch }} replace />; + } + + if (isInvalidPage) { + return redirectToFirstPage(); } // Later loads keep showing the previous books until the new ones arrive, - // unless it takes a while - if ((loading && !books?.length) || 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?.length) || slowLoading || suggestionsLoading) { return ( <BooksLayout> <SortSelect /> @@ -198,7 +204,7 @@ export default function BooksPage() { books={suggestions} searchListParams={suggestionParams.toString()} /> - <BookPagination + <ItemPagination totalPages={Math.ceil(suggestionCount / BOOK_PAGE_LIMIT)} /> </section> @@ -222,7 +228,7 @@ export default function BooksPage() { <BooksLayout resultCount={totalCount}> <SortSelect /> <BookList books={books} /> - <BookPagination totalPages={Math.ceil(totalCount / BOOK_PAGE_LIMIT)} /> + <ItemPagination totalPages={Math.ceil(totalCount / BOOK_PAGE_LIMIT)} /> </BooksLayout> ); } diff --git a/frontend/app/routes/profile.test.tsx b/frontend/app/routes/profile.test.tsx new file mode 100644 index 0000000..465a336 --- /dev/null +++ b/frontend/app/routes/profile.test.tsx @@ -0,0 +1,96 @@ +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. +// 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 } }, + result: { + data: { + favoriteBooks: { + __typename: "BookSearchResult", + totalCount: 0, + books: [], + }, + favoriteGenres: [], + }, + }, + maxUsageCount: Number.POSITIVE_INFINITY, + }; +} + +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/routes/profile.tsx b/frontend/app/routes/profile.tsx index d6a7895..02dd4ae 100644 --- a/frontend/app/routes/profile.tsx +++ b/frontend/app/routes/profile.tsx @@ -1,9 +1,9 @@ -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 { ItemPagination } from "~/components/ItemPagination/ItemPagination"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; import { ReviewList } from "~/components/ReviewList/ReviewList"; import { Avatar, AvatarFallback } from "~/components/ui/Avatar"; @@ -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, firstPageSearch } = 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,14 @@ export default function ProfilePage() { return <Navigate to="/login" replace />; } - if ((!books || books.length === 0) && !loading && page > 1) { - return <Navigate to="/profile" replace />; + // 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 <Navigate to={{ search: firstPageSearch }} replace />; } if ( - reviewPage === null || + isInvalidReviewPage || (reviewPage > 1 && myReviews.reviews?.length === 0) ) { // The page is invalid or has no reviews, e.g. after reviews were deleted @@ -197,7 +201,7 @@ export default function ProfilePage() { ))} </ul> )} - {totalPages > 1 && <BookPagination totalPages={totalPages} />} + {totalPages > 1 && <ItemPagination totalPages={totalPages} />} </section> <section diff --git a/frontend/app/test/session.ts b/frontend/app/test/session.ts index c344490..2804622 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,