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} 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 ( +
+ + Genres + + + {showAll && ( + setSearch(e.target.value)} + /> + )} + + + {shownGenres.map((genre, index) => ( + + toggleGenre(genre, checked)} + /> + + {genre} + + + ))} + + + {showAll && shownGenres.length === 0 && ( +

No genres found.

+ )} + + +
+ ); +} + +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 ( -
- +
+ Book length (pages) {searchParams.toString()}

; +} + +// The labels of the shown options, in order +function shownOptions() { + return screen + .getAllByText(/./, { selector: "label" }) + .map((label) => label.textContent); +} + +function renderFilter(url: string, options = LANGUAGES) { + const Stub = createRoutesStub([ + { + path: "/", + Component: () => ( + <> + + + + ), + }, + ]); + render(); +} + +describe("RadioFilter", () => { + it("shows any and the 5 most common options, with any checked", () => { + renderFilter("/"); + + expect(shownOptions()).toEqual(["Any", ...LANGUAGES.slice(0, 5)]); + expect(screen.getByRole("radio", { name: "Any" })).toBeChecked(); + }); + + it("sets the chosen option in the URL and goes back to page 1", async () => { + const user = userEvent.setup(); + renderFilter("/?page=3"); + + await user.click(screen.getByRole("radio", { name: "Spanish" })); + + await waitFor(() => + expect(screen.getByTestId("params")).toHaveTextContent( + /^language=Spanish$/, + ), + ); + }); + + it("removes the filter when choosing any", async () => { + const user = userEvent.setup(); + renderFilter("/?language=French"); + + expect(screen.getByRole("radio", { name: "French" })).toBeChecked(); + + await user.click(screen.getByRole("radio", { name: "Any" })); + + await waitFor(() => + expect(screen.getByTestId("params")).toBeEmptyDOMElement(), + ); + }); + + it("shows a chosen option that is not among the most common", () => { + renderFilter("/?language=Portuguese"); + + expect(screen.getByRole("radio", { name: "Portuguese" })).toBeChecked(); + }); + + it("searches all options after clicking show all", async () => { + const user = userEvent.setup(); + renderFilter("/"); + + await user.click( + screen.getByRole("button", { name: "Show all 7 languages" }), + ); + await user.type( + screen.getByRole("searchbox", { name: "Search languages" }), + "an", + ); + + expect(shownOptions()).toEqual(["Any", "Spanish", "German", "Indonesian"]); + }); + + it("has no show all button when all options fit", () => { + renderFilter("/", ["English", "French"]); + + expect( + screen.queryByRole("button", { name: /Show all/ }), + ).not.toBeInTheDocument(); + }); +}); diff --git a/frontend/app/components/books/RadioFilter/RadioFilter.tsx b/frontend/app/components/books/RadioFilter/RadioFilter.tsx new file mode 100644 index 00000000..114a052b --- /dev/null +++ b/frontend/app/components/books/RadioFilter/RadioFilter.tsx @@ -0,0 +1,116 @@ +import { useId, useState } from "react"; +import { useSearchParams } from "react-router"; +import { Button } from "~/components/ui/Button"; +import { + Field, + FieldLabel, + FieldLegend, + FieldSet, +} from "~/components/ui/Field"; +import { Input } from "~/components/ui/Input"; +import { RadioGroup, RadioGroupItem } from "~/components/ui/RadioGroup"; +import { useBookSearchParams } from "~/hooks/useBookSearchParams"; + +const TOP_OPTIONS_COUNT = 5; + +interface RadioFilterProps { + legend: string; + // The search param, which is also the filter name + param: "language" | "bookFormat"; + options: string[]; + // Used in "Show all ..." and "Search ...", for example "languages" + pluralName: string; +} + +// A filter where one option (or "Any") can be chosen from a long list +function RadioFilter({ legend, param, options, pluralName }: RadioFilterProps) { + const [, setSearchParams] = useSearchParams(); + const { filters } = useBookSearchParams(); + 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[param]; + + // Like in GenreFilter, the most common options keep their order, and a + // selected option outside them is added first + const topOptions = options.slice(0, TOP_OPTIONS_COUNT); + const shownOptions = showAll + ? options.filter((option) => + option.toLowerCase().includes(search.trim().toLowerCase()), + ) + : [ + ...(selected && !topOptions.includes(selected) ? [selected] : []), + ...topOptions, + ]; + + function selectOption(value: string) { + setSearchParams((searchParams) => { + if (value === "any") { + searchParams.delete(param); + } else { + searchParams.set(param, value); + } + searchParams.delete("page"); + return searchParams; + }); + } + + return ( +
+ + {legend} + + + {showAll && ( + setSearch(e.target.value)} + /> + )} + + selectOption(String(value))} + className="-m-1 p-1 gap-3 max-h-72 overflow-y-auto" + > + {["any", ...shownOptions].map((option, index) => ( + + + + {option === "any" ? "Any" : option} + + + ))} + + {showAll && shownOptions.length === 0 && ( +

No {pluralName} found.

+ )} + + {options.length > TOP_OPTIONS_COUNT && ( + + )} +
+ ); +} + +export { RadioFilter }; diff --git a/frontend/app/components/books/SearchBar/SearchBar.tsx b/frontend/app/components/books/SearchBar/SearchBar.tsx index fc12e91c..38f37a80 100644 --- a/frontend/app/components/books/SearchBar/SearchBar.tsx +++ b/frontend/app/components/books/SearchBar/SearchBar.tsx @@ -11,21 +11,18 @@ import { import { Button } from "~/components/ui/Button"; import { Badge } from "~/components/ui/Badge"; import { - Drawer, - DrawerClose, - DrawerContent, - DrawerHeader, - DrawerTitle, - DrawerTrigger, - DrawerDescription, - DrawerFooter, -} from "~/components/ui/Drawer"; -import { toast } from "~/components/ui/Toast"; + Sheet, + SheetClose, + SheetContent, + SheetFooter, + SheetTitle, + SheetTrigger, +} from "~/components/ui/Sheet"; import { useSearchParams } from "react-router"; import { useDebounce } from "~/hooks/useDebounce"; -import { FILTER_KEYS, useBookSearchParams } from "~/hooks/useBookSearchParams"; -import { useIsMobile } from "~/hooks/useIsMobile"; +import { useBookSearchParams } from "~/hooks/useBookSearchParams"; import { MAX_QUERY_LENGTH } from "~/lib/constants"; +import { toast } from "~/components/ui/Toast"; const SEARCH_DEBOUNCE_MS = 500; @@ -34,7 +31,7 @@ interface SearchBarProps { } function SearchBar({ resultCount }: SearchBarProps) { - const { query, filters } = useBookSearchParams(); + const { query, activeFiltersCount } = useBookSearchParams(); const [, setSearchParams] = useSearchParams(); const [inputField, setInputField] = useState(query); @@ -51,8 +48,6 @@ function SearchBar({ resultCount }: SearchBarProps) { // We don't want to stack multiple toasts on top of each other. const tooLongToastOpenRef = useRef(false); - const isMobile = useIsMobile(); - useEffect(() => { if (debouncedQuery !== inputField || debouncedQuery === query) { return; @@ -79,24 +74,7 @@ function SearchBar({ resultCount }: SearchBarProps) { newQueryFromInputRef.current = false; }, [debouncedQuery, inputField, query, setSearchParams]); - // The count of filters currently applied, so we can show a badge on the filter button. - const filtersCount = Object.values(filters).filter( - (value) => value !== undefined, - ).length; - - 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; - }); - }; - - const filtersDescription = `${filtersCount} ${filtersCount === 1 ? "filter" : "filters"} active`; + const filtersDescription = `${activeFiltersCount} ${activeFiltersCount === 1 ? "filter" : "filters"} active`; return (
@@ -140,74 +118,47 @@ function SearchBar({ resultCount }: SearchBarProps) { )} - - + } > - {filtersCount > 0 && ( + {activeFiltersCount > 0 && ( - {filtersCount} + {activeFiltersCount} )} - - - - - Filter books - - - -
+ + + {/* Names the sheet for screen readers. The filters show their own heading */} + Filter books + {/* Only the filters scroll, so the "Show books" button below is always visible. + The top padding leaves room for the close (X) button */} +
-
- - - - {filtersDescription} - - - - {resultCount !== undefined - ? `Show ${resultCount} ${resultCount === 1 ? "result" : "results"}` - : "Show results"} - - } - /> - -
-
+ + + }> + {resultCount === undefined + ? "Show books" + : `Show ${resultCount.toLocaleString("en")} ${resultCount === 1 ? "book" : "books"}`} + + + +
); } diff --git a/frontend/app/components/ui/Accordion.tsx b/frontend/app/components/ui/Accordion.tsx new file mode 100644 index 00000000..e1d1b0a2 --- /dev/null +++ b/frontend/app/components/ui/Accordion.tsx @@ -0,0 +1,77 @@ +import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion"; +import { cn } from "cn"; +import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; + +function Accordion({ className, ...props }: AccordionPrimitive.Root.Props) { + return ( + + ); +} + +function AccordionItem({ className, ...props }: AccordionPrimitive.Item.Props) { + return ( + + ); +} + +function AccordionTrigger({ + className, + children, + ...props +}: AccordionPrimitive.Trigger.Props) { + return ( + + + {children} + + + + + ); +} + +function AccordionContent({ + className, + children, + ...props +}: AccordionPrimitive.Panel.Props) { + return ( + +
+ {children} +
+
+ ); +} + +export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }; diff --git a/frontend/app/components/ui/Checkbox.tsx b/frontend/app/components/ui/Checkbox.tsx new file mode 100644 index 00000000..afc3c91d --- /dev/null +++ b/frontend/app/components/ui/Checkbox.tsx @@ -0,0 +1,25 @@ +import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"; +import { cn } from "cn"; +import { CheckIcon } from "lucide-react"; + +function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) { + return ( + + + + + + ); +} + +export { Checkbox }; diff --git a/frontend/app/components/ui/Combobox.tsx b/frontend/app/components/ui/Combobox.tsx deleted file mode 100644 index 345d91ba..00000000 --- a/frontend/app/components/ui/Combobox.tsx +++ /dev/null @@ -1,300 +0,0 @@ -"use client"; - -import * as React from "react"; -import { Combobox as ComboboxPrimitive } from "@base-ui/react"; -import { cn } from "cn"; - -import { Button } from "~/components/ui/Button"; -import { - InputGroup, - InputGroupAddon, - InputGroupButton, - InputGroupInput, -} from "~/components/ui/InputGroup"; -import { ChevronDownIcon, XIcon, CheckIcon } from "lucide-react"; - -const Combobox = ComboboxPrimitive.Root; - -function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) { - return ; -} - -function ComboboxTrigger({ - className, - children, - ...props -}: ComboboxPrimitive.Trigger.Props) { - return ( - - {children} - - - ); -} - -function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) { - return ( - } - className={cn(className)} - {...props} - > - - - ); -} - -function ComboboxInput({ - className, - children, - disabled = false, - showTrigger = true, - showClear = false, - ...props -}: ComboboxPrimitive.Input.Props & { - showTrigger?: boolean; - showClear?: boolean; -}) { - return ( - - } - {...props} - /> - - {showTrigger && ( - } - data-slot="input-group-button" - className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent" - disabled={disabled} - /> - )} - {showClear && } - - {children} - - ); -} - -function ComboboxContent({ - className, - side = "bottom", - sideOffset = 6, - align = "start", - alignOffset = 0, - anchor, - ...props -}: ComboboxPrimitive.Popup.Props & - Pick< - ComboboxPrimitive.Positioner.Props, - "side" | "align" | "sideOffset" | "alignOffset" | "anchor" - >) { - return ( - - - - - - ); -} - -function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) { - return ( - - ); -} - -function ComboboxItem({ - className, - children, - ...props -}: ComboboxPrimitive.Item.Props) { - return ( - - {children} - - } - > - - - - ); -} - -function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) { - return ( - - ); -} - -function ComboboxLabel({ - className, - ...props -}: ComboboxPrimitive.GroupLabel.Props) { - return ( - - ); -} - -function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) { - return ( - - ); -} - -function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) { - return ( - - ); -} - -function ComboboxSeparator({ - className, - ...props -}: ComboboxPrimitive.Separator.Props) { - return ( - - ); -} - -function ComboboxChips({ - className, - ...props -}: React.ComponentPropsWithRef & - ComboboxPrimitive.Chips.Props) { - return ( - - ); -} - -function ComboboxChip({ - className, - children, - showRemove = true, - ...props -}: ComboboxPrimitive.Chip.Props & { - showRemove?: boolean; -}) { - return ( - - {children} - {showRemove && ( - } - className="-ml-1 opacity-50 hover:opacity-100" - data-slot="combobox-chip-remove" - > - - - )} - - ); -} - -function ComboboxChipsInput({ - className, - ...props -}: ComboboxPrimitive.Input.Props) { - return ( - - ); -} - -function useComboboxAnchor() { - return React.useRef(null); -} - -export { - Combobox, - ComboboxInput, - ComboboxContent, - ComboboxList, - ComboboxItem, - ComboboxGroup, - ComboboxLabel, - ComboboxCollection, - ComboboxEmpty, - ComboboxSeparator, - ComboboxChips, - ComboboxChip, - ComboboxChipsInput, - ComboboxTrigger, - ComboboxValue, - useComboboxAnchor, -}; diff --git a/frontend/app/components/ui/Drawer.tsx b/frontend/app/components/ui/Drawer.tsx deleted file mode 100644 index c777cdb7..00000000 --- a/frontend/app/components/ui/Drawer.tsx +++ /dev/null @@ -1,225 +0,0 @@ -import * as React from "react"; -import { Drawer as DrawerPrimitive } from "@base-ui/react/drawer"; -import { cn } from "cn"; - -interface DrawerContextProps { - hasSnapPoints: boolean; - modal: DrawerPrimitive.Root.Props["modal"]; - showSwipeHandle: boolean; - swipeDirection: NonNullable; -} - -const DrawerContext = React.createContext(null); - -function useDrawer() { - const context = React.use(DrawerContext); - - if (!context) { - throw new Error("useDrawer must be used within a Drawer."); - } - - return context; -} - -function Drawer({ - modal = true, - showSwipeHandle = false, - snapPoints, - swipeDirection = "down", - ...props -}: DrawerPrimitive.Root.Props & { - showSwipeHandle?: boolean; -}) { - const hasSnapPoints = snapPoints != null && snapPoints.length > 0; - const contextValue = React.useMemo( - () => ({ hasSnapPoints, modal, showSwipeHandle, swipeDirection }), - [hasSnapPoints, modal, showSwipeHandle, swipeDirection], - ); - - return ( - - - - ); -} - -function DrawerTrigger({ ...props }: DrawerPrimitive.Trigger.Props) { - return ; -} - -function DrawerPortal({ ...props }: DrawerPrimitive.Portal.Props) { - return ; -} - -function DrawerClose({ ...props }: DrawerPrimitive.Close.Props) { - return ; -} - -function DrawerOverlay({ - className, - ...props -}: DrawerPrimitive.Backdrop.Props) { - return ( - - ); -} - -function DrawerSwipeHandle({ - className, - ...props -}: React.ComponentProps<"div">) { - return ( -