Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/.prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pnpm-lock.yaml
*.generated.*
db-data
test-db-data
drizzle
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
104 changes: 104 additions & 0 deletions frontend/app/components/selectedBook/BookBrowser/BookBrowser.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Pagination aria-label="Browse books" className="mt-8">
<PaginationContent className="gap-8">
<PaginationItem>
<PaginationPrevious
to={{
pathname: `/book/${previousBook?.id ?? bookId}`,
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?.id ?? bookId}`,
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>
);
}

export { BookBrowser };
59 changes: 59 additions & 0 deletions frontend/app/hooks/useBrowseBooks.ts
Original file line number Diff line number Diff line change
@@ -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 };
130 changes: 126 additions & 4 deletions frontend/app/routes/book/selectedBook.test.tsx
Original file line number Diff line number Diff line change
@@ -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", () => ({
Expand All @@ -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.
Expand Down Expand Up @@ -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");
});
});
Loading