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
17 changes: 17 additions & 0 deletions docs/choices-and-reasoning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
`useDataIsDelayed` and `useLogOut`.
- **Snapshot test** for `BookCard`. The rendered HTML is stored in
Expand Down
20 changes: 5 additions & 15 deletions frontend/app/components/books/BookFilters/BookFilters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import {
AccordionTrigger,
} from "~/components/ui/Accordion";
import { Badge } from "~/components/ui/Badge";
import { useSearchParams } from "react-router";
import type { FilterOption } from "~/api/types";
import { FILTER_KEYS, useBookSearchParams } from "~/hooks/useBookSearchParams";
import {
useBookSearchParams,
useResetFilters,
} from "~/hooks/useBookSearchParams";
import { useBookFacets } from "~/hooks/useBookFacets";
import { MinRatingsFilter } from "~/components/books/MinRatingsFilter/MinRatingsFilter";
import { PagesFilter } from "~/components/books/PagesFilter/PagesFilter";
Expand Down Expand Up @@ -53,8 +55,8 @@ function FilterSection({
}

function BookFilters() {
const [, setSearchParams] = useSearchParams();
const { query, filters, activeFiltersCount } = useBookSearchParams();
const clearFilters = useResetFilters();

// Only the options that give results for the current search are shown
const facets = useBookFacets({ query, filters });
Expand All @@ -81,18 +83,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 (
<section aria-labelledby={headingId} className="flex flex-col gap-4">
<header className="flex items-center justify-between">
Expand Down
20 changes: 19 additions & 1 deletion frontend/app/hooks/useBookSearchParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
44 changes: 14 additions & 30 deletions frontend/app/hooks/useSuggestedBooks.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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,
};
}

Expand Down
113 changes: 32 additions & 81 deletions frontend/app/routes/books.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -205,24 +205,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 () => {
Expand Down Expand Up @@ -315,7 +311,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: [
Expand All @@ -333,116 +331,69 @@ 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);
});

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,
}),
Expand Down
Loading