From 3ff54f40c94e3f4c1dad25e0177440768a77ec4f Mon Sep 17 00:00:00 2001 From: Johannes Horn Date: Mon, 23 Nov 2026 09:21:04 +0100 Subject: [PATCH 1/2] feat(frontend): only suggest similar titles when a search has no results --- .../books/BookFilters/BookFilters.tsx | 20 +--- frontend/app/hooks/useBookSearchParams.ts | 20 +++- frontend/app/hooks/useSuggestedBooks.ts | 44 +++---- frontend/app/routes/books.test.tsx | 113 +++++------------- frontend/app/routes/books.tsx | 51 +++++--- frontend/e2e/books.spec.ts | 8 +- 6 files changed, 111 insertions(+), 145 deletions(-) diff --git a/frontend/app/components/books/BookFilters/BookFilters.tsx b/frontend/app/components/books/BookFilters/BookFilters.tsx index 22e86a4..ed6720d 100644 --- a/frontend/app/components/books/BookFilters/BookFilters.tsx +++ b/frontend/app/components/books/BookFilters/BookFilters.tsx @@ -6,8 +6,10 @@ import { AccordionTrigger, } from "~/components/ui/Accordion"; import { Badge } from "~/components/ui/Badge"; -import { useSearchParams } from "react-router"; -import { FILTER_KEYS, useBookSearchParams } from "~/hooks/useBookSearchParams"; +import { + useBookSearchParams, + useResetFilters, +} from "~/hooks/useBookSearchParams"; import { useBookFilters } from "~/hooks/useBookFilters"; import { MinRatingsFilter } from "~/components/books/MinRatingsFilter/MinRatingsFilter"; import { PagesFilter } from "~/components/books/PagesFilter/PagesFilter"; @@ -52,8 +54,8 @@ function FilterSection({ } function BookFilters() { - const [, setSearchParams] = useSearchParams(); const { filters, activeFiltersCount } = useBookSearchParams(); + const clearFilters = useResetFilters(); const { languages, bookFormats } = useBookFilters(); // The filters can be rendered twice (sidebar on desktop, sheet on mobile), @@ -71,18 +73,6 @@ function BookFilters() { ...(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 (
diff --git a/frontend/app/hooks/useBookSearchParams.ts b/frontend/app/hooks/useBookSearchParams.ts index e8233f0..de24a15 100644 --- a/frontend/app/hooks/useBookSearchParams.ts +++ b/frontend/app/hooks/useBookSearchParams.ts @@ -52,4 +52,22 @@ function useBookSearchParams() { return { query, page, filters, sort, activeFiltersCount }; } -export { FILTER_KEYS, useBookSearchParams }; +// Returns a function that removes all filters, but keeps the search query and +// sort. Used by the reset buttons in the filters and on the page without results +function useResetFilters() { + const [, setSearchParams] = useSearchParams(); + + return () => { + 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; + }); + }; +} + +export { useBookSearchParams, useResetFilters }; diff --git a/frontend/app/hooks/useSuggestedBooks.ts b/frontend/app/hooks/useSuggestedBooks.ts index c9e0717..612c1d9 100644 --- a/frontend/app/hooks/useSuggestedBooks.ts +++ b/frontend/app/hooks/useSuggestedBooks.ts @@ -1,16 +1,17 @@ import type { BookFilters } from "~/api/types"; import type { BookSortKey } from "~/api/bookSort"; import { useSearchBooks } from "~/hooks/useSearchBooks"; -import { BOOK_PAGE_LIMIT, MIN_RATINGS } from "~/lib/constants"; +import { BOOK_PAGE_LIMIT } from "~/lib/constants"; /** * Suggested books when a search has no results. * - * The suggested books are books with a title or author similar to the search query. - * If none are found, we use top-rated books instead. - * For top-rated books, we remove the filters if there is no search query, - * since that means the filters are the reason there are no results. - * The sort only applies to similar books, top-rated books are always sorted by rating. + * The suggested books are books with a title or author similar to the search + * query, for example when the query has a typo. They use the same filters and + * sort as the search. + * + * We only suggest books that are related to what the user searched for. When + * nothing is similar, or there is no search query, there are no suggestions. */ function useSuggestedBooks({ query, @@ -25,40 +26,23 @@ function useSuggestedBooks({ sort?: BookSortKey; enabled: boolean; }) { - const offset = (page - 1) * BOOK_PAGE_LIMIT; + // Without a search query, there is nothing to be similar to + const searching = enabled && query !== ""; const similar = useSearchBooks({ filters, query, fuzzy: true, limit: BOOK_PAGE_LIMIT, - offset, + offset: (page - 1) * BOOK_PAGE_LIMIT, sort, - enabled: enabled && query !== "", - }); - - const hasSimilar = similar.totalCount > 0; - const keptFilters = query ? filters : {}; - - const topRated = useSearchBooks({ - filters: { - ...keptFilters, - minRatings: Math.max(keptFilters.minRatings ?? 0, MIN_RATINGS), - }, - query: "", - limit: BOOK_PAGE_LIMIT, - offset, - sort: "rating_desc", - enabled: enabled && !similar.loading && !hasSimilar, + enabled: searching, }); - const result = hasSimilar ? similar : topRated; - return { - books: result.books, - totalCount: result.totalCount, - similarTitles: hasSimilar, - loading: enabled && !result.books && !result.error, + books: similar.books, + totalCount: similar.totalCount, + loading: searching && !similar.books && !similar.error, }; } diff --git a/frontend/app/routes/books.test.tsx b/frontend/app/routes/books.test.tsx index c936da0..a393e5b 100644 --- a/frontend/app/routes/books.test.tsx +++ b/frontend/app/routes/books.test.tsx @@ -168,24 +168,20 @@ describe("BooksPage", () => { { query: "zzzz", fuzzy: true, limit: 12, offset: 0 }, [], ), - searchBooksMock( - { - query: "", - minRatings: 10000, - sortBy: "RATING", - sortDirection: "DESC", - limit: 12, - offset: 0, - }, - [], - ), ], }); expect( - await screen.findByText("No books found for this search"), + await screen.findByText('No books found for "zzzz"'), + ).toBeInTheDocument(); + expect( + screen.getByText("Check the spelling, or try fewer or different words."), ).toBeInTheDocument(); expect(screen.getByText("0 results")).toBeInTheDocument(); + // Without filters, there is nothing to reset + expect( + screen.queryByRole("button", { name: "Reset filters" }), + ).not.toBeInTheDocument(); }); it("suggests books with similar titles when the search has a typo", async () => { @@ -278,7 +274,9 @@ describe("BooksPage", () => { ).toBeInTheDocument(); }); - it("suggests top-rated books with the same filters when the search has no results", async () => { + // The only requests that are mocked are the search and the search for + // similar titles. A request for other books to show instead would fail + it("does not suggest unrelated books when nothing is similar to the search", async () => { renderRoutes(routes, { initialEntries: ["/books?q=zzzz&genres=Fantasy"], mocks: [ @@ -296,96 +294,55 @@ describe("BooksPage", () => { }, [], ), - searchBooksMock({ - query: "", - genres: ["Fantasy"], - minRatings: 10000, - sortBy: "RATING", - sortDirection: "DESC", - limit: 12, - offset: 0, - }), ], }); expect( - await screen.findByRole("heading", { name: "Suggested books" }), + await screen.findByText('No books found for "zzzz"'), ).toBeInTheDocument(); expect( - screen.getByText( - "No books found for this search. However, we found some top-rated books matching your filters.", - ), + screen.getByText("Check the spelling, or try removing some filters."), ).toBeInTheDocument(); - expect(await findBookCards()).toHaveLength(3); expect( - screen.queryByRole("combobox", { name: "Sort by" }), + screen.queryByRole("heading", { name: "Suggested books" }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: /^Favorite / }), ).not.toBeInTheDocument(); }); - it("suggests top-rated books without filters when the filters have no results", async () => { + it("does not look for similar titles when only the filters give no results", async () => { + const user = userEvent.setup(); renderRoutes(routes, { - initialEntries: ["/books?genres=Fantasy&maxPages=1"], + initialEntries: ["/books?genres=Fantasy&maxPages=1&sort=title_asc"], mocks: [ searchBooksMock( { query: "", genres: ["Fantasy"], maxPages: 1, + sortBy: "TITLE", + sortDirection: "ASC", limit: 12, offset: 0, }, [], ), + // The search after the filters are reset. The sort is kept searchBooksMock({ query: "", - minRatings: 10000, - sortBy: "RATING", - sortDirection: "DESC", + sortBy: "TITLE", + sortDirection: "ASC", limit: 12, offset: 0, }), ], }); - expect( - await screen.findByRole("heading", { name: "Suggested books" }), - ).toBeInTheDocument(); - expect( - screen.getByText( - "No books found for this search. However, we found some top-rated books you might like.", - ), - ).toBeInTheDocument(); - expect(await findBookCards()).toHaveLength(3); - }); + expect(await screen.findByText("No books found")).toBeInTheDocument(); + expect(screen.getByText("Try removing some filters.")).toBeInTheDocument(); - it("keeps the user's minimum number of ratings in the suggestions when it is higher", async () => { - renderRoutes(routes, { - initialEntries: ["/books?q=zzzz&minRatings=50000"], - mocks: [ - searchBooksMock( - { query: "zzzz", minRatings: 50000, limit: 12, offset: 0 }, - [], - ), - searchBooksMock( - { - query: "zzzz", - fuzzy: true, - minRatings: 50000, - limit: 12, - offset: 0, - }, - [], - ), - searchBooksMock({ - query: "", - minRatings: 50000, - sortBy: "RATING", - sortDirection: "DESC", - limit: 12, - offset: 0, - }), - ], - }); + await user.click(screen.getByRole("button", { name: "Reset filters" })); expect(await findBookCards()).toHaveLength(3); }); @@ -393,19 +350,13 @@ describe("BooksPage", () => { it("browses through the suggestions on a suggested book's details page", async () => { const user = userEvent.setup(); renderRoutes(routes, { - initialEntries: ["/books?q=zzzz"], + initialEntries: ["/books?q=blade+itslef"], // The suggestions are reused from Apollo's cache on the details page. mocks: [ - searchBooksMock({ query: "zzzz", limit: 12, offset: 0 }, []), - searchBooksMock( - { query: "zzzz", fuzzy: true, limit: 12, offset: 0 }, - [], - ), + searchBooksMock({ query: "blade itslef", limit: 12, offset: 0 }, []), searchBooksMock({ - query: "", - minRatings: 10000, - sortBy: "RATING", - sortDirection: "DESC", + query: "blade itslef", + fuzzy: true, limit: 12, offset: 0, }), diff --git a/frontend/app/routes/books.tsx b/frontend/app/routes/books.tsx index 3fb1838..9370186 100644 --- a/frontend/app/routes/books.tsx +++ b/frontend/app/routes/books.tsx @@ -4,13 +4,17 @@ import { SearchBar } from "~/components/books/SearchBar/SearchBar"; import { BookCard, BookCardSkeleton } from "~/components/BookCard/BookCard"; import { SortSelect } from "~/components/books/SortSelect/SortSelect"; import { PageBreadcrumb } from "~/components/PageBreadcrumb/PageBreadcrumb"; -import { useBookSearchParams } from "~/hooks/useBookSearchParams"; +import { + useBookSearchParams, + useResetFilters, +} from "~/hooks/useBookSearchParams"; import { useSuggestedBooks } from "~/hooks/useSuggestedBooks"; import { usePageParam } from "~/hooks/usePageParam"; import { Navigate, useSearchParams } from "react-router"; import { useDataIsDelayed } from "~/hooks/useDataIsDelayed"; import type { ReactNode } from "react"; import { BookFilters } from "~/components/books/BookFilters/BookFilters"; +import { Button } from "~/components/ui/Button"; import { BOOK_PAGE_LIMIT } from "~/lib/constants"; // Loading that takes longer than this shows skeletons instead of the previous books @@ -101,6 +105,7 @@ export default function BooksPage() { const { query, page, filters, sort, activeFiltersCount } = useBookSearchParams(); const { isInvalid: isInvalidPage, firstPageSearch } = usePageParam(); + const resetFilters = useResetFilters(); const { books, totalCount, loading, error } = useSearchBooks({ filters, @@ -114,10 +119,11 @@ export default function BooksPage() { // state first const slowLoading = useDataIsDelayed(loading, SLOW_LOADING_MS); + // When a search has no results, we look for books with a similar title or + // author, for example when the search has a typo const { books: suggestions, totalCount: suggestionCount, - similarTitles, loading: suggestionsLoading, } = useSuggestedBooks({ query, @@ -190,15 +196,10 @@ export default function BooksPage() { Suggested books

- No books found for this search. However, we found some{" "} - {similarTitles - ? "books with similar titles or authors" - : query && activeFiltersCount > 0 - ? "top-rated books matching your filters" - : "top-rated books you might like"} - . + No books found for this search. However, we found some books + with similar titles or authors.

- {similarTitles && } +
0; + let hint = "Try removing some filters."; + if (query) { + hint = hasFilters + ? "Check the spelling, or try removing some filters." + : "Check the spelling, or try fewer or different words."; + } + return ( -

- No books found for this search -

+

+ + {query ? `No books found for "${query}"` : "No books found"} + + {hint} +

+ {hasFilters && ( + + )} +
); } diff --git a/frontend/e2e/books.spec.ts b/frontend/e2e/books.spec.ts index 121aeb7..d6be929 100644 --- a/frontend/e2e/books.spec.ts +++ b/frontend/e2e/books.spec.ts @@ -113,13 +113,15 @@ test("a book can be opened, browsed and left again", async ({ page }) => { await expect(page).toHaveURL("books?q=potter"); }); -test("a search without matches suggests other books", async ({ page }) => { +test("a search without matches shows no other books", async ({ page }) => { await page.goto("books?q=xqzvwkjhqzx"); await expect( - page.getByRole("status").filter({ hasText: "No books found" }), + page + .getByRole("status") + .filter({ hasText: 'No books found for "xqzvwkjhqzx"' }), ).toBeVisible(); - await expect(bookCards(page).first()).toBeVisible(); + await expect(bookCards(page)).toHaveCount(0); }); test("an unknown book shows a not found message", async ({ page }) => { From e0f2625bd7748f62b87c0affa011c15efbfed0bf Mon Sep 17 00:00:00 2001 From: Johannes Horn Date: Mon, 23 Nov 2026 09:21:04 +0100 Subject: [PATCH 2/2] docs: explain why we only suggest similar titles --- docs/choices-and-reasoning.md | 17 +++++++++++++++++ frontend/README.md | 5 +++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/choices-and-reasoning.md b/docs/choices-and-reasoning.md index 53403ee..25c93cc 100644 --- a/docs/choices-and-reasoning.md +++ b/docs/choices-and-reasoning.md @@ -78,6 +78,23 @@ We discussed whether a filter that is chosen for the user is more annoying than We do not offer sorting by author (#100). The author field in the dataset is free text and can hold several names, like "Author One, Author Two". We have no guarantee that the authors of a book are always listed in the same order, or whether a name is written as "First Last" or "Last, First", so sorting on this field would often give an order that looks random. Authors can be found with the search field instead, which searches both titles and authors. +## A search without results only suggests similar titles + +When a search has no results, we look for books with a title or author that is similar to the search text, and show those with a text that explains why. This helps with typos: "Lord fo the rings" finds The Lord of the Rings. If nothing is similar, or the user has only used filters, we show that no books were found, with a hint to check the spelling and a button that resets the filters when some are active. + +We used to fall back to top-rated books when nothing was similar. Our lecturer pointed out that these are not what the user searched for, so showing them is more confusing than helpful (#159). A search for a book we don't have should say so clearly. + +Similar titles are found with the `pg_trgm` extension in PostgreSQL, which compares the search text with the titles and authors and gives a similarity between 0 and 1. We use the default threshold of 0.6. We measured some searches against the whole dataset: + +| Search | Similarity to "The Lord of the Rings" | Similar books found | +| ------------------- | ------------------------------------- | ------------------- | +| `lord of the rngs` | 0.76 | 23 | +| `Lord fo the rings` | 0.71 | 6 | +| `Lord fo thy rngs` | 0.40 | 0 | +| `tolkein` | 0.50 | 0 | + +So the suggestions help with one typo in a longer search, but not with several typos or a typo in a short word. A lower threshold would catch more typos, but it also risks showing "similar" books for searches that have nothing to do with them, which is what we wanted to get rid of. We have kept the default, and a typo that is not caught gets the hint to check the spelling instead. + ## Selecting several genres shows books in any of them When several genres are selected, we show books that belong to at least one of them (OR), not all of them (AND). This is because it widens the search instead of quickly ending up with no results. diff --git a/frontend/README.md b/frontend/README.md index 52c94d3..2949dbe 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -102,8 +102,9 @@ intended change without catching real bugs. favorites and reviews. - **Page tests** for the home page, the books page, the book page and the profile page (`app/routes/`): the whole page is rendered with mocked API - responses, for example searching, the suggestions when a search has no - results, errors from the API, and browsing from one book to the next. + responses, for example searching, the similar titles and the empty state + when a search has no results, errors from the API, and browsing from one + book to the next. - **Hook tests** for `useBookSearchParams`, `usePageParam`, `useCountUp` and `useDataIsDelayed`. - **Snapshot test** for `BookCard`. The rendered HTML is stored in