Skip to content
2 changes: 1 addition & 1 deletion frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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: () => <BookPagination totalPages={5} />,
Component: () => <ItemPagination totalPages={5} />,
},
]);

Expand All @@ -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();
Expand Down Expand Up @@ -101,7 +101,7 @@ describe("BookPagination", () => {
{
path: "/",
Component: () => (
<BookPagination totalPages={5} searchParam="reviewPage" />
<ItemPagination totalPages={5} searchParam="reviewPage" />
),
},
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -125,4 +125,4 @@ function BookPagination({
);
}

export { BookPagination };
export { ItemPagination };
4 changes: 2 additions & 2 deletions frontend/app/components/ReviewList/ReviewList.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -62,7 +62,7 @@ function ReviewList({ reviews, totalCount, headingId }: ReviewListProps) {
))}
</ul>
{totalPages > 1 && (
<BookPagination
<ItemPagination
totalPages={totalPages}
searchParam={REVIEW_PAGE_PARAM}
scrollTargetId={headingId}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 (
<section
Expand Down Expand Up @@ -58,7 +60,7 @@ function BookReviews({

<Separator />

{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
<Navigate to={{ search: firstPageSearch }} replace />
) : error ? (
Expand Down
17 changes: 2 additions & 15 deletions frontend/app/hooks/useBookSearchParams.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(), {
Expand All @@ -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)}`);
Expand Down
12 changes: 4 additions & 8 deletions frontend/app/hooks/useBookSearchParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
Expand Down Expand Up @@ -56,4 +52,4 @@ function useBookSearchParams() {
return { query, page, filters, sort, activeFiltersCount };
}

export { FILTER_KEYS, parsePageNum, useBookSearchParams };
export { FILTER_KEYS, useBookSearchParams };
50 changes: 50 additions & 0 deletions frontend/app/hooks/usePageParam.test.tsx
Original file line number Diff line number Diff line change
@@ -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 }) => (
<MemoryRouter initialEntries={[url]}>{children}</MemoryRouter>
),
});
}

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");
});
});
24 changes: 24 additions & 0 deletions frontend/app/hooks/usePageParam.ts
Original file line number Diff line number Diff line change
@@ -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 };
18 changes: 0 additions & 18 deletions frontend/app/hooks/useReviews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -237,7 +220,6 @@ function useReviewMutations({ bookId }: { bookId: string }) {
}

export {
useReviewPage,
useBookReviews,
useMyReview,
useMyReviews,
Expand Down
19 changes: 8 additions & 11 deletions frontend/app/hooks/useSuggestedBooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
16 changes: 16 additions & 0 deletions frontend/app/routes/book/selectedBook.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down
Loading