diff --git a/backend/.prettierignore b/backend/.prettierignore
index 630777b..24baeab 100644
--- a/backend/.prettierignore
+++ b/backend/.prettierignore
@@ -1,4 +1,5 @@
pnpm-lock.yaml
*.generated.*
db-data
+test-db-data
drizzle
diff --git a/frontend/app/components/ItemPagination/ItemPagination.test.tsx b/frontend/app/components/ItemPagination/ItemPagination.test.tsx
index 6f55337..392af03 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);
diff --git a/frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx b/frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx
new file mode 100644
index 0000000..e4228d9
--- /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/hooks/useBrowseBooks.ts b/frontend/app/hooks/useBrowseBooks.ts
new file mode 100644
index 0000000..46c995a
--- /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 0b14399..6f788eb 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 a6ef958..8a233f1 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";
@@ -7,66 +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 { useSearchBooks } from "~/hooks/useSearchBooks";
-import { useBookSearchParams } from "~/hooks/useBookSearchParams";
-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";
+import { BookBrowser } from "~/components/selectedBook/BookBrowser/BookBrowser";
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 });
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,
- });
-
- const { books: suggestedBooks } = useSuggestedBooks({
- query,
- filters,
- page,
- sort,
- enabled: origin === "suggestions",
- });
-
- const books =
- origin === "favorites"
- ? favoriteBooks
- : origin === "suggestions"
- ? suggestedBooks
- : searchBooks;
-
if (loading) {
return (
@@ -92,13 +45,6 @@ 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;
-
return (
{/* Uses instead of meta() to allow the document title to be defined dynamically in the route. */}
@@ -200,37 +146,7 @@ export default function SelectedBookPage({ params }: Route.ComponentProps) {
-
-
-
- span]:block",
- !previousBook && DISABLED_STYLE,
- )}
- />
-
-
- span]:block", !nextBook && DISABLED_STYLE)}
- />
-
-
-
+
);
diff --git a/frontend/e2e/books.spec.ts b/frontend/e2e/books.spec.ts
index d6be929..d252e2a 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");