diff --git a/frontend/app/components/BookCard/BookCard.tsx b/frontend/app/components/BookCard/BookCard.tsx
index 34d4f44a..71d283a8 100644
--- a/frontend/app/components/BookCard/BookCard.tsx
+++ b/frontend/app/components/BookCard/BookCard.tsx
@@ -2,6 +2,7 @@ import { StarIcon } from "lucide-react";
import { BookCover } from "~/components/BookCover/BookCover";
import { FavoriteButton } from "~/components/FavoriteButton/FavoriteButton";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/Card";
+import { Skeleton } from "~/components/ui/Skeleton";
import { Link, useLocation, useSearchParams } from "react-router";
import type { SearchBook } from "~/hooks/useSearchBooks";
@@ -77,4 +78,19 @@ function BookCard({ book, searchListParams }: BookCardProps) {
);
}
-export { BookCard };
+// A placeholder with the same layout as BookCard, so the grid doesn't jump
+// when the books load. Hidden from screen readers, so the page should
+// announce the loading itself
+function BookCardSkeleton() {
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+export { BookCard, BookCardSkeleton };
diff --git a/frontend/app/components/books/BookFilters/BookFilters.test.tsx b/frontend/app/components/books/BookFilters/BookFilters.test.tsx
index d66329d0..3ecbdfe6 100644
--- a/frontend/app/components/books/BookFilters/BookFilters.test.tsx
+++ b/frontend/app/components/books/BookFilters/BookFilters.test.tsx
@@ -1,14 +1,14 @@
import { describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
+import userEvent, { type UserEvent } from "@testing-library/user-event";
import { createRoutesStub, Link, useSearchParams } from "react-router";
import { BookFilters } from "~/components/books/BookFilters/BookFilters";
-import { toast } from "~/components/ui/Toast";
vi.mock("~/hooks/useBookFilters", () => ({
useBookFilters: () => ({
genres: ["Fantasy", "Romance", "Science Fiction"],
languages: ["English", "French", "Spanish"],
+ bookFormats: ["Paperback", "Hardcover"],
loading: false,
error: undefined,
}),
@@ -42,80 +42,85 @@ const Stub = createRoutesStub([
},
]);
+// Each filter is in an accordion section that has to be opened first,
+// unless the filter is already in use.
+async function openSection(user: UserEvent, name: string) {
+ await user.click(screen.getByRole("button", { name }));
+}
+
describe("FilterBooksSection", () => {
- it("shows the selected genres from the URL", () => {
- render();
+ it("shows how many options of each filter are selected", () => {
+ render(
+ ,
+ );
- expect(screen.getByText("Fantasy")).toBeInTheDocument();
- expect(screen.getByText("Romance")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Genres 2 selected" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Language 1 selected" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Book format" }),
+ ).toBeInTheDocument();
});
- it("adds a selected genre to the URL", async () => {
- const user = userEvent.setup();
- render();
+ it("opens the genres and the filters that are in use", () => {
+ render();
- await user.type(screen.getByLabelText("Genres"), "Sci");
- await user.click(
- await screen.findByRole("option", { name: "Science Fiction" }),
+ expect(screen.getByRole("button", { name: "Genres" })).toHaveAttribute(
+ "aria-expanded",
+ "true",
);
-
- await waitFor(() =>
- expect(screen.getByTestId("genres")).toHaveTextContent(
- "Fantasy,Science Fiction",
- ),
+ expect(
+ screen.getByRole("button", { name: "Language 1 selected" }),
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByRole("button", { name: "Book format" })).toHaveAttribute(
+ "aria-expanded",
+ "false",
);
});
- it("shows an error and keeps the genres when selecting more than 15", async () => {
- const addToast = vi.spyOn(toast, "add");
+ it("sets the minimum number of ratings in the URL", async () => {
const user = userEvent.setup();
- const fifteenGenres = Array.from({ length: 15 }, (_, i) => `Genre${i}`);
- const query = fifteenGenres.map((genre) => `genres=${genre}`).join("&");
- render();
+ render();
- await user.type(screen.getByLabelText("Genres"), "Sci");
- await user.click(
- await screen.findByRole("option", { name: "Science Fiction" }),
- );
+ await openSection(user, "Minimum ratings");
+ await user.click(screen.getByRole("radio", { name: "1,000+ ratings" }));
- expect(addToast).toHaveBeenCalledWith(
- expect.objectContaining({ type: "error" }),
- );
- expect(screen.getByTestId("genres")).toHaveTextContent(
- fifteenGenres.join(","),
+ await waitFor(() =>
+ expect(screen.getByTestId("minRatings")).toHaveTextContent("1000"),
);
});
- it("shows the selected language from the URL", () => {
- render();
-
- expect(screen.getByLabelText("Language")).toHaveValue("French");
- });
-
- it("sets the selected language in the URL", async () => {
+ it("removes the minimum number of ratings when choosing any", async () => {
const user = userEvent.setup();
- render();
+ render();
- await user.type(screen.getByLabelText("Language"), "Spa");
- await user.click(await screen.findByRole("option", { name: "Spanish" }));
+ await user.click(screen.getByRole("radio", { name: "Any" }));
await waitFor(() =>
- expect(screen.getByTestId("language")).toHaveTextContent("Spanish"),
+ expect(screen.getByTestId("minRatings")).toBeEmptyDOMElement(),
);
});
- it("sets the minimum number of ratings in the URL", async () => {
+ it("removes all filters on reset", async () => {
const user = userEvent.setup();
- render();
-
- await user.click(screen.getByLabelText("Minimum ratings"));
- await user.click(
- await screen.findByRole("option", { name: "1,000+ ratings" }),
+ render(
+ ,
);
- await waitFor(() =>
- expect(screen.getByTestId("minRatings")).toHaveTextContent("1000"),
- );
+ await user.click(screen.getByRole("button", { name: "Reset" }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("genres")).toBeEmptyDOMElement();
+ expect(screen.getByTestId("language")).toBeEmptyDOMElement();
+ expect(screen.getByTestId("minRatings")).toBeEmptyDOMElement();
+ });
});
it("shows the page range from the URL", () => {
@@ -125,8 +130,10 @@ describe("FilterBooksSection", () => {
expect(screen.getByLabelText("Maximum pages")).toHaveValue(500);
});
- it("defaults the page range to 0 and the slider end", () => {
+ it("defaults the page range to 0 and the slider end", async () => {
+ const user = userEvent.setup();
render();
+ await openSection(user, "Book length (pages)");
expect(screen.getByLabelText("Minimum pages")).toHaveValue(0);
expect(screen.getByLabelText("Maximum pages")).toHaveValue(2000);
@@ -135,6 +142,7 @@ describe("FilterBooksSection", () => {
it("writes a typed max to the URL on Enter", async () => {
const user = userEvent.setup();
render();
+ await openSection(user, "Book length (pages)");
const maxInput = screen.getByLabelText("Maximum pages");
await user.clear(maxInput);
@@ -162,6 +170,7 @@ describe("FilterBooksSection", () => {
it("keeps focus when tabbing from min to max", async () => {
const user = userEvent.setup();
render();
+ await openSection(user, "Book length (pages)");
await user.type(screen.getByLabelText("Minimum pages"), "{Backspace}100");
await user.tab();
@@ -215,6 +224,7 @@ describe("FilterBooksSection", () => {
it("follows the URL again after a committed edit", async () => {
const user = userEvent.setup();
render();
+ await openSection(user, "Book length (pages)");
await user.type(
screen.getByLabelText("Minimum pages"),
diff --git a/frontend/app/components/books/BookFilters/BookFilters.tsx b/frontend/app/components/books/BookFilters/BookFilters.tsx
index 85f8d8b1..b9f9d3e0 100644
--- a/frontend/app/components/books/BookFilters/BookFilters.tsx
+++ b/frontend/app/components/books/BookFilters/BookFilters.tsx
@@ -1,160 +1,148 @@
+import { useId, type ReactNode } from "react";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "~/components/ui/Accordion";
+import { Badge } from "~/components/ui/Badge";
import { useSearchParams } from "react-router";
-import { useBookSearchParams } from "~/hooks/useBookSearchParams";
+import { FILTER_KEYS, useBookSearchParams } from "~/hooks/useBookSearchParams";
import { useBookFilters } from "~/hooks/useBookFilters";
-import {
- Combobox,
- ComboboxChip,
- ComboboxChips,
- ComboboxChipsInput,
- ComboboxContent,
- ComboboxEmpty,
- ComboboxInput,
- ComboboxItem,
- ComboboxList,
- ComboboxValue,
- useComboboxAnchor,
-} from "~/components/ui/Combobox";
import { MinRatingsFilter } from "~/components/books/MinRatingsFilter/MinRatingsFilter";
import { PagesFilter } from "~/components/books/PagesFilter/PagesFilter";
-import { toast } from "~/components/ui/Toast";
-import { MAX_GENRES } from "~/lib/constants";
+import { GenreFilter } from "~/components/books/GenreFilter/GenreFilter";
+import { RadioFilter } from "~/components/books/RadioFilter/RadioFilter";
+import { Button } from "~/components/ui/Button";
+
+interface FilterSectionProps {
+ value: string;
+ title: string;
+ activeCount: number;
+ children: ReactNode;
+}
+
+// One filter in the Accordion. The badge shows how many of its options are selected
+function FilterSection({
+ value,
+ title,
+ activeCount,
+ children,
+}: FilterSectionProps) {
+ return (
+
+
+
+ {/* The space keeps screen readers from reading "Genres2 selected" */}
+ {title}{" "}
+ {activeCount > 0 && (
+
+ {activeCount}
+ {`${activeCount} selected`}
+
+ )}
+
+
+
+ {children}
+
+
+ );
+}
function BookFilters() {
const [, setSearchParams] = useSearchParams();
- const { filters } = useBookSearchParams();
- const { genres, languages, bookFormats } = useBookFilters();
- const genresAnchor = useComboboxAnchor();
+ const { filters, activeFiltersCount } = useBookSearchParams();
+ const { languages, bookFormats } = useBookFilters();
+
+ // The filters can be rendered twice (sidebar on desktop, sheet on mobile),
+ // so we need a unique id
+ const headingId = useId();
+
+ const genresCount = filters.genres?.length ?? 0;
+
+ // Genres start open, and so do the other filters that are in use
+ const initSections = [
+ "genres",
+ ...(filters.language ? ["language"] : []),
+ ...(filters.bookFormat ? ["bookFormat"] : []),
+ ...(filters.minRatings === undefined ? [] : ["minRatings"]),
+ ...(filters.pages ? ["pages"] : []),
+ ];
+
+ const clearFilters = () => {
+ setSearchParams((searchParams) => {
+ FILTER_KEYS.forEach((key) => searchParams.delete(key));
+
+ // Reset the page to 1 when clearing filters.
+ // A missing "page" search param means page 1
+ searchParams.delete("page");
+
+ return searchParams;
+ });
+ };
return (
-
- -
-
- {
- if (selected.length > MAX_GENRES) {
- toast.add({
- description: `You can select up to ${MAX_GENRES} genres.`,
- type: "error",
- });
- return;
- }
- setSearchParams((searchParams) => {
- searchParams.delete("genres");
- selected.forEach((genre) => searchParams.append("genres", genre));
- searchParams.delete("page");
- return searchParams;
- });
- }}
+
+
+
+ Filter Books
+
+
-
- -
-
- {
- setSearchParams((searchParams) => {
- if (language) {
- searchParams.set("language", language);
- } else {
- searchParams.delete("language");
- }
- searchParams.delete("page");
- return searchParams;
- });
- }}
+ Reset
+
+
+
+
+
+
+
+
-
-
- No languages found.
-
- {(language: string) => (
-
- {language}
-
- )}
-
-
-
-
- -
-
- {
- setSearchParams((searchParams) => {
- if (bookFormat) {
- searchParams.set("bookFormat", bookFormat);
- } else {
- searchParams.delete("bookFormat");
- }
- searchParams.delete("page");
- return searchParams;
- });
- }}
+
+
-
-
- No book formats found.
-
- {(bookFormat: string) => (
-
- {bookFormat}
-
- )}
-
-
-
-
- -
-
-
- -
-
-
-
+
+
+
+
+
+
+
+
+
);
}
diff --git a/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx b/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx
new file mode 100644
index 00000000..e73967e7
--- /dev/null
+++ b/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx
@@ -0,0 +1,140 @@
+import { describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { createRoutesStub, useSearchParams } from "react-router";
+import { GenreFilter } from "~/components/books/GenreFilter/GenreFilter";
+import { toast } from "~/components/ui/Toast";
+import { MAX_GENRES } from "~/lib/constants";
+
+// Sorted by book count, like the API returns them
+const GENRES = [
+ "Fiction",
+ "Fantasy",
+ "Romance",
+ "Young Adult",
+ "Classics",
+ "Mystery",
+ "Nonfiction",
+ "Historical",
+ "Science Fiction",
+ "Poetry",
+];
+
+vi.mock("~/hooks/useBookFilters", () => ({
+ useBookFilters: () => ({ genres: GENRES }),
+}));
+
+// Shows the genres in the URL so tests can assert what was written to it.
+function SearchParamProbe() {
+ const [searchParams] = useSearchParams();
+ return {searchParams.getAll("genres").join(",")}
;
+}
+
+const Stub = createRoutesStub([
+ {
+ path: "/",
+ Component: () => (
+ <>
+
+
+ >
+ ),
+ },
+]);
+
+// The labels of the shown checkboxes, in order
+function shownGenres() {
+ return screen
+ .getAllByText(/./, { selector: "label" })
+ .map((label) => label.textContent);
+}
+
+describe("GenreFilter", () => {
+ it("shows the 8 most common genres", () => {
+ render();
+
+ expect(shownGenres()).toEqual(GENRES.slice(0, 8));
+ expect(
+ screen.getByRole("button", { name: "Show all 10 genres" }),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps the order of the genres when one is checked", async () => {
+ const user = userEvent.setup();
+ render();
+
+ await user.click(screen.getByRole("checkbox", { name: "Mystery" }));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("genres")).toHaveTextContent("Mystery"),
+ );
+ expect(shownGenres()).toEqual(GENRES.slice(0, 8));
+ });
+
+ it("shows a selected genre that is not among the most common", async () => {
+ const user = userEvent.setup();
+ render();
+
+ const poetry = screen.getByRole("checkbox", { name: "Poetry" });
+ expect(poetry).toBeChecked();
+
+ await user.click(poetry);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("genres")).toBeEmptyDOMElement(),
+ );
+ });
+
+ it("shows an error and keeps the genres when selecting too many", async () => {
+ const addToast = vi.spyOn(toast, "add");
+ const user = userEvent.setup();
+ const maxGenres = Array.from({ length: MAX_GENRES }, (_, i) => `Genre${i}`);
+ const query = maxGenres.map((genre) => `genres=${genre}`).join("&");
+ render();
+
+ await user.click(screen.getByRole("checkbox", { name: "Fiction" }));
+
+ expect(addToast).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "error" }),
+ );
+ expect(screen.getByTestId("genres")).toHaveTextContent(maxGenres.join(","));
+ });
+
+ it("can uncheck a genre when the maximum is selected", async () => {
+ const user = userEvent.setup();
+ const maxGenres = Array.from({ length: MAX_GENRES }, (_, i) => `Genre${i}`);
+ const query = maxGenres.map((genre) => `genres=${genre}`).join("&");
+ render();
+
+ await user.click(screen.getByRole("checkbox", { name: "Genre0" }));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("genres")).toHaveTextContent(
+ maxGenres.slice(1).join(","),
+ ),
+ );
+ });
+
+ it("searches all genres after clicking show all", async () => {
+ const user = userEvent.setup();
+ render();
+
+ await user.click(
+ screen.getByRole("button", { name: "Show all 10 genres" }),
+ );
+ await user.type(
+ screen.getByRole("searchbox", { name: "Search genres" }),
+ "fic",
+ );
+
+ expect(shownGenres()).toEqual(["Fiction", "Nonfiction", "Science Fiction"]);
+
+ await user.type(
+ screen.getByRole("searchbox", { name: "Search genres" }),
+ "zzz",
+ );
+
+ expect(screen.queryAllByRole("checkbox")).toHaveLength(0);
+ expect(screen.getByText("No genres found.")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/app/components/books/GenreFilter/GenreFilter.tsx b/frontend/app/components/books/GenreFilter/GenreFilter.tsx
new file mode 100644
index 00000000..1a1f0656
--- /dev/null
+++ b/frontend/app/components/books/GenreFilter/GenreFilter.tsx
@@ -0,0 +1,116 @@
+import { useId, useState } from "react";
+import { useSearchParams } from "react-router";
+import { Button } from "~/components/ui/Button";
+import { Checkbox } from "~/components/ui/Checkbox";
+import {
+ Field,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSet,
+} from "~/components/ui/Field";
+import { Input } from "~/components/ui/Input";
+import { toast } from "~/components/ui/Toast";
+import { useBookFilters } from "~/hooks/useBookFilters";
+import { useBookSearchParams } from "~/hooks/useBookSearchParams";
+import { MAX_GENRES } from "~/lib/constants";
+
+const TOP_GENRES_COUNT = 8;
+
+function GenreFilter() {
+ const [, setSearchParams] = useSearchParams();
+ const { filters } = useBookSearchParams();
+ const { genres } = useBookFilters();
+ const [showAll, setShowAll] = useState(false);
+ const [search, setSearch] = useState("");
+
+ // The filters can be rendered twice (sidebar on desktop, sheet on mobile),
+ // so we need a unique id. Names can also have spaces, so we use the index
+ const baseId = useId();
+
+ const selected = filters.genres ?? [];
+
+ const topGenres = genres.slice(0, TOP_GENRES_COUNT);
+
+ // The most common genres keep their order, so checking one doesn't move the
+ // list. Selected genres outside them are added first, so they can be
+ // unchecked. "Show all" shows every genre that matches the search instead
+ const shownGenres = showAll
+ ? genres.filter((genre) =>
+ genre.toLowerCase().includes(search.trim().toLowerCase()),
+ )
+ : [...selected.filter((genre) => !topGenres.includes(genre)), ...topGenres];
+
+ function toggleGenre(genre: string, checked: boolean) {
+ if (checked && selected.length >= MAX_GENRES) {
+ toast.add({
+ description: `You can select up to ${MAX_GENRES} genres.`,
+ type: "error",
+ });
+ return;
+ }
+
+ setSearchParams((searchParams) => {
+ const newGenres = checked
+ ? [...selected, genre]
+ : selected.filter((selectedGenre) => selectedGenre !== genre);
+
+ searchParams.delete("genres");
+ newGenres.forEach((newGenre) => searchParams.append("genres", newGenre));
+ searchParams.delete("page");
+ return searchParams;
+ });
+ }
+
+ return (
+
+ );
+}
+
+export { GenreFilter };
diff --git a/frontend/app/components/books/MinRatingsFilter/MinRatingsFilter.tsx b/frontend/app/components/books/MinRatingsFilter/MinRatingsFilter.tsx
index 7f8a0592..d72c3b48 100644
--- a/frontend/app/components/books/MinRatingsFilter/MinRatingsFilter.tsx
+++ b/frontend/app/components/books/MinRatingsFilter/MinRatingsFilter.tsx
@@ -1,12 +1,13 @@
+import { useId } from "react";
import { useSearchParams } from "react-router";
import { useBookSearchParams } from "~/hooks/useBookSearchParams";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "~/components/ui/Select";
+ Field,
+ FieldLabel,
+ FieldLegend,
+ FieldSet,
+} from "~/components/ui/Field";
+import { RadioGroup, RadioGroupItem } from "~/components/ui/RadioGroup";
const items = [
{ value: "any", label: "Any" },
@@ -20,18 +21,23 @@ function MinRatingsFilter() {
const [, setSearchParams] = useSearchParams();
const { filters } = useBookSearchParams();
+ // The filters can be rendered twice (sidebar on desktop, sheet on mobile),
+ // so we need a unique id
+ const baseId = useId();
+
return (
- <>
-
-
- >
+
+
+ ))}
+
+
);
}
diff --git a/frontend/app/components/books/PagesFilter/PagesFilter.tsx b/frontend/app/components/books/PagesFilter/PagesFilter.tsx
index 6f439992..c6dac8a1 100644
--- a/frontend/app/components/books/PagesFilter/PagesFilter.tsx
+++ b/frontend/app/components/books/PagesFilter/PagesFilter.tsx
@@ -1,4 +1,4 @@
-import { useState, type ComponentProps } from "react";
+import { useId, useState, type ComponentProps } from "react";
import { useSearchParams } from "react-router";
import { useBookSearchParams } from "~/hooks/useBookSearchParams";
import { Input } from "~/components/ui/Input";
@@ -16,6 +16,10 @@ function PagesFilter() {
const [, setSearchParams] = useSearchParams();
const { filters } = useBookSearchParams();
+ // The filters can be rendered twice (sidebar on desktop, sheet on mobile),
+ // so we need a unique id
+ const labelId = useId();
+
const [draft, setDraft] = useState(null);
const urlMin = filters.pages?.min ?? 0;
@@ -58,12 +62,12 @@ function PagesFilter() {
}
return (
-