From 96c2e09bc52e83b3f5c60b57a9e9258f167b237e Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Wed, 25 Nov 2026 20:56:19 +0100 Subject: [PATCH 1/5] chore: make prettier ignore test db data folder --- backend/.prettierignore | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/.prettierignore b/backend/.prettierignore index 630777bb..24baeab0 100644 --- a/backend/.prettierignore +++ b/backend/.prettierignore @@ -1,4 +1,5 @@ pnpm-lock.yaml *.generated.* db-data +test-db-data drizzle From c3a46fa864e32a249940d4668d919b8fb3acbdb3 Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Wed, 25 Nov 2026 21:25:50 +0100 Subject: [PATCH 2/5] refactor: remove duplicate prefers reduced motion in test --- frontend/app/components/ItemPagination/ItemPagination.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/frontend/app/components/ItemPagination/ItemPagination.test.tsx b/frontend/app/components/ItemPagination/ItemPagination.test.tsx index 6f553373..392af039 100644 --- a/frontend/app/components/ItemPagination/ItemPagination.test.tsx +++ b/frontend/app/components/ItemPagination/ItemPagination.test.tsx @@ -48,7 +48,6 @@ describe("ItemPagination", () => { }); it("moves to the next or previous page and scrolls to the top", async () => { - prefersReducedMotion(false); // jsdom cannot scroll; replace window.scrollTo so it does not warn. const scrollTo = vi.spyOn(window, "scrollTo").mockImplementation(vi.fn()); prefersReducedMotion(false); From 71912da6d29d381666d160f50bd9aa07af02672e Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski Date: Wed, 25 Nov 2026 21:40:03 +0100 Subject: [PATCH 3/5] feat: browse to last/next page of books on selectedBook page --- frontend/app/hooks/useBrowseBooks.ts | 59 ++++++++ .../app/routes/book/selectedBook.test.tsx | 130 +++++++++++++++++- frontend/app/routes/book/selectedBook.tsx | 91 ++++++------ 3 files changed, 233 insertions(+), 47 deletions(-) create mode 100644 frontend/app/hooks/useBrowseBooks.ts diff --git a/frontend/app/hooks/useBrowseBooks.ts b/frontend/app/hooks/useBrowseBooks.ts new file mode 100644 index 00000000..46c995aa --- /dev/null +++ b/frontend/app/hooks/useBrowseBooks.ts @@ -0,0 +1,59 @@ +import { authClient } from "~/api/auth"; +import { useBookSearchParams } from "~/hooks/useBookSearchParams"; +import { useFavoriteBooks } from "~/hooks/useFavoriteBooks"; +import { useSearchBooks } from "~/hooks/useSearchBooks"; +import { BOOK_PAGE_LIMIT, FAVORITE_BOOKS_PAGE_LIMIT } from "~/lib/constants"; + +/** + * One page of the list the user came from to the book details page: the + * search results, the suggestions or the favorites. Used to browse to the + * previous and next book. + */ +function useBrowseBooks({ + origin, + page, + enabled = true, +}: { + origin: string | null; + page: number; + enabled?: boolean; +}) { + const { query, filters, sort } = useBookSearchParams(); + const { data: session } = authClient.useSession(); + const isFavorites = origin === "favorites"; + const isSuggestions = origin === "suggestions"; + + // Suggestions are a fuzzy search, and only exist for a search query. + // See useSuggestedBooks + const search = useSearchBooks({ + filters, + query, + fuzzy: isSuggestions || undefined, + limit: BOOK_PAGE_LIMIT, + offset: (page - 1) * BOOK_PAGE_LIMIT, + sort, + enabled: enabled && !isFavorites && (!isSuggestions || query !== ""), + }); + + const favorites = useFavoriteBooks({ + page, + // Only logged in users have favorites + enabled: enabled && isFavorites && !!session, + }); + + if (isFavorites) { + return { + books: favorites.books, + totalPages: Math.ceil(favorites.totalCount / FAVORITE_BOOKS_PAGE_LIMIT), + }; + } + + return { + // While loading, useSearchBooks returns the results for the previous + // variables, which could be another page and link to the wrong book + books: search.loading ? undefined : search.books, + totalPages: Math.ceil(search.totalCount / BOOK_PAGE_LIMIT), + }; +} + +export { useBrowseBooks }; diff --git a/frontend/app/routes/book/selectedBook.test.tsx b/frontend/app/routes/book/selectedBook.test.tsx index 0b143993..6f788eb4 100644 --- a/frontend/app/routes/book/selectedBook.test.tsx +++ b/frontend/app/routes/book/selectedBook.test.tsx @@ -1,11 +1,18 @@ import { describe, expect, it, vi } from "vitest"; -import { screen } from "@testing-library/react"; +import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; +import type { MockLink } from "@apollo/client/testing"; +import { authClient } from "~/api/auth"; +import { FAVORITE_BOOK_IDS, FAVORITE_BOOKS } from "~/hooks/useFavoriteBooks"; import SelectedBookPage from "~/routes/book/selectedBook"; -import { apiBook } from "~/test/fixtures/books"; -import { bookMock, searchBooksMock } from "~/test/mocks"; +import { apiBook, apiSearchBooks } from "~/test/fixtures/books"; +import { + bookMock, + defaultSearchVariables, + searchBooksMock, +} from "~/test/mocks"; import { renderRoutes } from "~/test/renderRoutes"; -import { loggedOut } from "~/test/session"; +import { loggedIn, loggedOut } from "~/test/session"; // FavoriteButton reads the session. Logged out, it sends no GraphQL requests. vi.mock("~/api/auth", () => ({ @@ -14,6 +21,30 @@ vi.mock("~/api/auth", () => ({ const routes = [{ path: "/book/:bookId", Component: SelectedBookPage }]; +// The first book on page 2, after the three search results on page 1 +const apiNextPageBook = { + ...apiSearchBooks[0], + id: 4, + title: "Last Argument of Kings", +}; + +// The favorites are refetched every time the page renders them +function favoriteBooksMock( + offset: number, + books: typeof apiSearchBooks, +): MockLink.MockedResponse { + return { + request: { query: FAVORITE_BOOKS, variables: { limit: 3, offset } }, + result: { + data: { + favoriteBooks: { __typename: "BookSearchResult", totalCount: 4, books }, + favoriteGenres: [], + }, + }, + maxUsageCount: Number.POSITIVE_INFINITY, + }; +} + describe("SelectedBookPage", () => { // The page loads the book itself, and the current search results so the // user can browse to the previous and next book. @@ -86,4 +117,95 @@ describe("SelectedBookPage", () => { await screen.findByText("The second book in The First Law trilogy."), ).toBeInTheDocument(); }); + + it("browses past the last book on the page to the next page and back", async () => { + const user = userEvent.setup(); + renderRoutes(routes, { + initialEntries: ["/book/3"], + mocks: [ + bookMock(3, { ...apiBook, id: 3, title: "Good Omens" }), + bookMock(4, { ...apiBook, id: 4, title: "Last Argument of Kings" }), + searchBooksMock(defaultSearchVariables, apiSearchBooks, 13), + searchBooksMock( + { ...defaultSearchVariables, offset: 12 }, + [apiNextPageBook], + 13, + ), + ], + }); + + const next = () => screen.getByRole("link", { name: "Go to next book" }); + await waitFor(() => + expect(next()).toHaveAttribute("aria-disabled", "false"), + ); + await user.click(next()); + + expect( + await screen.findByRole("heading", { name: "Last Argument of Kings" }), + ).toBeInTheDocument(); + // Going back to the list shows the page with this book + expect( + screen.getByRole("button", { name: "Go back to search results" }), + ).toHaveAttribute("href", "/books?page=2"); + + await user.click(screen.getByRole("link", { name: "Go to previous book" })); + + expect( + await screen.findByRole("heading", { name: "Good Omens" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Go back to search results" }), + ).toHaveAttribute("href", "/books"); + }); + + it("cannot browse past the last search result", async () => { + renderRoutes(routes, { + initialEntries: ["/book/3"], + mocks: [ + bookMock(3, { ...apiBook, id: 3, title: "Good Omens" }), + searchBooksMock(), + ], + }); + + await waitFor(() => + expect( + screen.getByRole("link", { name: "Go to previous book" }), + ).toHaveAttribute("aria-disabled", "false"), + ); + expect( + screen.getByRole("link", { name: "Go to next book" }), + ).toHaveAttribute("aria-disabled", "true"); + }); + + it("browses to the next page of the favorites", async () => { + vi.mocked(authClient.useSession).mockReturnValue(loggedIn); + const user = userEvent.setup(); + renderRoutes(routes, { + initialEntries: ["/book/3?origin=favorites"], + mocks: [ + bookMock(3, { ...apiBook, id: 3, title: "Good Omens" }), + bookMock(4, { ...apiBook, id: 4, title: "Last Argument of Kings" }), + favoriteBooksMock(0, apiSearchBooks), + favoriteBooksMock(3, [apiNextPageBook]), + { + request: { query: FAVORITE_BOOK_IDS }, + result: { data: { favoriteBookIds: [1, 2, 3, 4] } }, + maxUsageCount: Number.POSITIVE_INFINITY, + }, + ], + }); + + const next = () => screen.getByRole("link", { name: "Go to next book" }); + await waitFor(() => + expect(next()).toHaveAttribute("aria-disabled", "false"), + ); + await user.click(next()); + + expect( + await screen.findByRole("heading", { name: "Last Argument of Kings" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Go back to search results" }), + ).toHaveAttribute("href", "/profile?page=2"); + }); }); diff --git a/frontend/app/routes/book/selectedBook.tsx b/frontend/app/routes/book/selectedBook.tsx index a6ef9588..b3a3afc9 100644 --- a/frontend/app/routes/book/selectedBook.tsx +++ b/frontend/app/routes/book/selectedBook.tsx @@ -1,5 +1,4 @@ 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"; @@ -16,57 +15,45 @@ import { } from "~/components/ui/Pagination"; import { Link, useSearchParams } from "react-router"; import { useBook } from "~/hooks/useBook"; -import { useSearchBooks } from "~/hooks/useSearchBooks"; -import { useBookSearchParams } from "~/hooks/useBookSearchParams"; +import { useBrowseBooks } from "~/hooks/useBrowseBooks"; +import { usePageParam } from "~/hooks/usePageParam"; import { cn } from "~/lib/utils"; -import { useFavoriteBooks } from "~/hooks/useFavoriteBooks"; -import { useSuggestedBooks } from "~/hooks/useSuggestedBooks"; import { BookRating } from "~/components/BookRating/BookRating"; import { BookReviews } from "~/components/selectedBook/BookReviews/BookReviews"; -import { BOOK_PAGE_LIMIT } from "~/lib/constants"; 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 { page } = usePageParam(); const origin = searchParams.get("origin"); const { book, loading, error } = useBook({ id: params.bookId }); const pageTitle = book ? `${book.title} | Readr` : "Book details | Readr"; - const { books: searchBooks } = useSearchBooks({ - filters, - query, - limit: BOOK_PAGE_LIMIT, - offset: (page - 1) * BOOK_PAGE_LIMIT, - sort, - enabled: origin !== "favorites" && origin !== "suggestions", - }); - - const { books: favoriteBooks } = useFavoriteBooks({ - page, - // Only logged in users have favorites - enabled: origin === "favorites" && !!session, - }); + // 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 { books, totalPages } = useBrowseBooks({ origin, page }); + const index = books?.findIndex((b) => b.id === params.bookId) ?? -1; + const lastIndex = (books?.length ?? 0) - 1; + + // On the first or last book of the page, browsing continues on the + // previous or next page, so that page is loaded too + let adjacentPage: number | undefined; + if (index === 0 && page > 1) { + adjacentPage = page - 1; + } else if (index >= 0 && index === lastIndex && page < totalPages) { + adjacentPage = page + 1; + } - const { books: suggestedBooks } = useSuggestedBooks({ - query, - filters, - page, - sort, - enabled: origin === "suggestions", + const { books: adjacentBooks } = useBrowseBooks({ + origin, + page: adjacentPage ?? page, + enabled: adjacentPage !== undefined, }); - const books = - origin === "favorites" - ? favoriteBooks - : origin === "suggestions" - ? suggestedBooks - : searchBooks; - if (loading) { return (
@@ -92,12 +79,30 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { const paramsWithoutOrigin = new URLSearchParams(searchParams); paramsWithoutOrigin.delete("origin"); - // 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; + const previousBook = + index > 0 + ? books?.[index - 1] + : adjacentPage === page - 1 + ? adjacentBooks?.at(-1) + : undefined; + const nextBook = + index >= 0 && index < lastIndex + ? books?.[index + 1] + : adjacentPage === page + 1 + ? adjacentBooks?.[0] + : undefined; + + // Browsing to a book on another page updates the page, so going back to + // the list shows the page with that book + function browseSearch(bookPage: number) { + const browseParams = new URLSearchParams(searchParams); + if (bookPage > 1) { + browseParams.set("page", String(bookPage)); + } else { + browseParams.delete("page"); + } + return browseParams.toString(); + } return (
@@ -206,7 +211,7 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { 0 ? page : page - 1), }} aria-label="Go to previous book" aria-disabled={!previousBook} @@ -221,7 +226,7 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { Date: Wed, 25 Nov 2026 21:45:53 +0100 Subject: [PATCH 4/5] refactor: move browsing books on selectedBook page to own component --- .../selectedBook/BookBrowser/BookBrowser.tsx | 104 ++++++++++++++++++ frontend/app/routes/book/selectedBook.tsx | 93 +--------------- 2 files changed, 106 insertions(+), 91 deletions(-) create mode 100644 frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx diff --git a/frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx b/frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx new file mode 100644 index 00000000..e4228d9c --- /dev/null +++ b/frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx @@ -0,0 +1,104 @@ +import { useSearchParams } from "react-router"; +import { + Pagination, + PaginationContent, + PaginationItem, + PaginationNext, + PaginationPrevious, +} from "~/components/ui/Pagination"; +import { useBrowseBooks } from "~/hooks/useBrowseBooks"; +import { usePageParam } from "~/hooks/usePageParam"; +import { cn } from "~/lib/utils"; + +const DISABLED_STYLE = "pointer-events-none opacity-50"; + +interface BookBrowserProps { + bookId: string; +} + +// Browses to the previous and next book in the list the user came from +function BookBrowser({ bookId }: BookBrowserProps) { + const [searchParams] = useSearchParams(); + const { page } = usePageParam(); + const origin = searchParams.get("origin"); + + // 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 { books, totalPages } = useBrowseBooks({ origin, page }); + const index = books?.findIndex((b) => b.id === bookId) ?? -1; + const lastIndex = (books?.length ?? 0) - 1; + + // On the first or last book of the page, browsing continues on the + // previous or next page, so that page is loaded too + let adjacentPage: number | undefined; + if (index === 0 && page > 1) { + adjacentPage = page - 1; + } else if (index >= 0 && index === lastIndex && page < totalPages) { + adjacentPage = page + 1; + } + + const { books: adjacentBooks } = useBrowseBooks({ + origin, + page: adjacentPage ?? page, + enabled: adjacentPage !== undefined, + }); + + const previousBook = + index > 0 + ? books?.[index - 1] + : adjacentPage === page - 1 + ? adjacentBooks?.at(-1) + : undefined; + const nextBook = + index >= 0 && index < lastIndex + ? books?.[index + 1] + : adjacentPage === page + 1 + ? adjacentBooks?.[0] + : undefined; + + // Browsing to a book on another page updates the page, so going back to + // the list shows the page with that book + function browseSearch(bookPage: number) { + const browseParams = new URLSearchParams(searchParams); + if (bookPage > 1) { + browseParams.set("page", String(bookPage)); + } else { + browseParams.delete("page"); + } + return browseParams.toString(); + } + + return ( + + + + 0 ? page : page - 1), + }} + aria-label="Go to previous book" + aria-disabled={!previousBook} + tabIndex={!previousBook ? -1 : undefined} // -1 means the link is skipped when tabbing + className={cn("[&>span]:block", !previousBook && DISABLED_STYLE)} + /> + + + span]:block", !nextBook && DISABLED_STYLE)} + /> + + + + ); +} + +export { BookBrowser }; diff --git a/frontend/app/routes/book/selectedBook.tsx b/frontend/app/routes/book/selectedBook.tsx index b3a3afc9..8a233f11 100644 --- a/frontend/app/routes/book/selectedBook.tsx +++ b/frontend/app/routes/book/selectedBook.tsx @@ -6,54 +6,20 @@ import { BookDescription } from "~/components/selectedBook/BookDescription/BookD import { Button } from "~/components/ui/Button"; import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/Card"; import { Separator } from "~/components/ui/Separator"; -import { - Pagination, - PaginationContent, - PaginationItem, - PaginationNext, - PaginationPrevious, -} from "~/components/ui/Pagination"; import { Link, useSearchParams } from "react-router"; import { useBook } from "~/hooks/useBook"; -import { useBrowseBooks } from "~/hooks/useBrowseBooks"; -import { usePageParam } from "~/hooks/usePageParam"; -import { cn } from "~/lib/utils"; import { BookRating } from "~/components/BookRating/BookRating"; import { BookReviews } from "~/components/selectedBook/BookReviews/BookReviews"; - -const DISABLED_STYLE = "pointer-events-none opacity-50"; +import { BookBrowser } from "~/components/selectedBook/BookBrowser/BookBrowser"; export default function SelectedBookPage({ params }: Route.ComponentProps) { const [searchParams] = useSearchParams(); - const { page } = usePageParam(); const origin = searchParams.get("origin"); const { book, loading, error } = useBook({ id: params.bookId }); const pageTitle = book ? `${book.title} | Readr` : "Book details | Readr"; - // 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 { books, totalPages } = useBrowseBooks({ origin, page }); - const index = books?.findIndex((b) => b.id === params.bookId) ?? -1; - const lastIndex = (books?.length ?? 0) - 1; - - // On the first or last book of the page, browsing continues on the - // previous or next page, so that page is loaded too - let adjacentPage: number | undefined; - if (index === 0 && page > 1) { - adjacentPage = page - 1; - } else if (index >= 0 && index === lastIndex && page < totalPages) { - adjacentPage = page + 1; - } - - const { books: adjacentBooks } = useBrowseBooks({ - origin, - page: adjacentPage ?? page, - enabled: adjacentPage !== undefined, - }); - if (loading) { return (
@@ -79,31 +45,6 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { const paramsWithoutOrigin = new URLSearchParams(searchParams); paramsWithoutOrigin.delete("origin"); - const previousBook = - index > 0 - ? books?.[index - 1] - : adjacentPage === page - 1 - ? adjacentBooks?.at(-1) - : undefined; - const nextBook = - index >= 0 && index < lastIndex - ? books?.[index + 1] - : adjacentPage === page + 1 - ? adjacentBooks?.[0] - : undefined; - - // Browsing to a book on another page updates the page, so going back to - // the list shows the page with that book - function browseSearch(bookPage: number) { - const browseParams = new URLSearchParams(searchParams); - if (bookPage > 1) { - browseParams.set("page", String(bookPage)); - } else { - browseParams.delete("page"); - } - return browseParams.toString(); - } - return (
{/* Uses instead of meta() to allow the document title to be defined dynamically in the route. */} @@ -205,37 +146,7 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) { <BookReviews key={book.id} bookId={book.id} bookTitle={book.title} /> - <Pagination aria-label="Browse books" className="mt-8"> - <PaginationContent className="gap-8"> - <PaginationItem> - <PaginationPrevious - to={{ - pathname: `/book/${(previousBook ?? book).id}`, - search: browseSearch(index > 0 ? page : page - 1), - }} - aria-label="Go to previous book" - aria-disabled={!previousBook} - tabIndex={!previousBook ? -1 : undefined} // -1 means the link is skipped when tabbing - className={cn( - "[&>span]:block", - !previousBook && DISABLED_STYLE, - )} - /> - </PaginationItem> - <PaginationItem> - <PaginationNext - to={{ - pathname: `/book/${(nextBook ?? book).id}`, - search: browseSearch(index < lastIndex ? page : page + 1), - }} - aria-label="Go to next book" - aria-disabled={!nextBook} - tabIndex={!nextBook ? -1 : undefined} // -1 means the link is skipped when tabbing - className={cn("[&>span]:block", !nextBook && DISABLED_STYLE)} - /> - </PaginationItem> - </PaginationContent> - </Pagination> + <BookBrowser bookId={book.id} /> </article> </main> ); From 11777a50bfdd14aced346869ea62c068c5c8518a Mon Sep 17 00:00:00 2001 From: Martin Alexander Kaminski <martakam@stud.ntnu.no> Date: Wed, 25 Nov 2026 22:16:58 +0100 Subject: [PATCH 5/5] test(e2e): add test for browsing to another page on selectedBook page --- frontend/e2e/books.spec.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/frontend/e2e/books.spec.ts b/frontend/e2e/books.spec.ts index d6be9299..d252e2a8 100644 --- a/frontend/e2e/books.spec.ts +++ b/frontend/e2e/books.spec.ts @@ -113,6 +113,28 @@ test("a book can be opened, browsed and left again", async ({ page }) => { await expect(page).toHaveURL("books?q=potter"); }); +test("browsing past the last book on a page continues on the next page", async ({ + page, +}) => { + await page.goto("books"); + + await bookCards(page).last().getByRole("link").click(); + await expect(page).toHaveURL(/\/book\/\d+$/); + const lastUrl = page.url(); + + // The link is disabled until the next page has loaded, and Playwright waits for it + await page.getByRole("link", { name: "Go to next book" }).click(); + await expect(page).toHaveURL(/\/book\/\d+\?page=2$/); + + await page.getByRole("link", { name: "Go to previous book" }).click(); + await expect(page).toHaveURL(lastUrl); + + await page.getByRole("link", { name: "Go to next book" }).click(); + await expect(page).toHaveURL(/\/book\/\d+\?page=2$/); + await page.getByRole("button", { name: "Go back to search results" }).click(); + await expect(page).toHaveURL("books?page=2"); +}); + test("a search without matches shows no other books", async ({ page }) => { await page.goto("books?q=xqzvwkjhqzx");