Suwatte

Search and filters

Write search, give the app sort options, build the filter controls, and divide search into scopes.

getSearchResults(request, page)

async getSearchResults(request: SearchRequest, page: number): Promise<PagedItemList> {
  const response = await this.client.get("/search", {
    params: {
      q: request.query ?? "",
      page,
      sort: request.sort?.key,
      order: request.sort?.ascending ? "asc" : "desc",
      ...this.mapFilters(request.filters),
    },
  });

  const json = await response.json();

  return {
    items: json.results.map(toItem),
    isLastPage: page >= json.total_pages,
  };
}

The page value starts at 1. The app sends it separately from the request.

The request holds:

Field Type When it is there
query string? A person typed text.
sort { key, ascending? }? You wrote getSortOptions.
filters object? You wrote getSearchFilters.
scopeId string? You wrote getSearchScopes, and a person selected a scope. See Search scopes.

Your code must accept a request with no query value. Global search and a browse with filters only can both make one.

Sort options

Write getSortOptions, and the search screen gets a sort control.

async getSortOptions(): Promise<SortOptions> {
  return {
    options: [
      { id: "relevance", title: "Relevance" },
      { id: "updated", title: "Recently updated" },
      { id: "rating", title: "Rating" },
    ],
  };
}

The option that a person selects comes back as request.sort.key.

The search screen also has a direction control. Its value comes back as request.sort.ascending. The control starts at descending, so ascending is false or is not there. Give one option for each field, and use the direction to select the order on the site. Do not give one option for each direction.

If the site cannot reverse its order, set disableOrdering: true. The app then hides the direction control.

Search filters

Write getSearchFilters, and the search screen gets filter controls. A filter uses the same view system as a settings page.

import { PickerFilter, SearchFilter, SelectFilter } from "@suwatte/toolchain";

async getSearchFilters(): Promise<SearchFilter[]> {
  return [
    SearchFilter(
      "genres",
      "Genres",
      SelectFilter(
        [
          { id: "action", title: "Action" },
          { id: "romance", title: "Romance" },
        ],
        true, // exclude
      ),
    ),
    SearchFilter(
      "status",
      "Status",
      PickerFilter([
        { id: "ongoing", title: "Ongoing" },
        { id: "completed", title: "Completed" },
      ]),
    ),
  ];
}

The toolchain has four kinds of filter: SelectFilter, PickerFilter, ToggleFilter and TextFilter. A PickerFilter value arrives as the id of one option. A ToggleFilter value arrives as a boolean, and a TextFilter value arrives as a string.

Include and exclude

A SelectFilter with exclude set to true gives a person three states for each option: include it, exclude it, or ignore it. The value arrives in this shape:

{ include: ["action"], exclude: ["romance"] }

This is important for genres, because “all except romance” is a normal need.

If the site cannot express an exclusion, leave exclude as false. Do not accept the input and then ignore it.

Map the filters to the site

The request.filters object uses the id values that you declared. Change them to what the site needs:

mapFilters(filters: Record<string, any> = {}) {
  const genres = filters.genres ?? { include: [], exclude: [] };
  return {
    included_tags: genres.include.join(","),
    excluded_tags: genres.exclude.join(","),
    status: filters.status,
  };
}

Search scopes

A site can have more than one place to search, such as series, reading lists or the library of the person. Write getSearchScopes, and the search screen gets a Search In menu.

async getSearchScopes(): Promise<SearchScopes> {
  const signedIn = Boolean(await this.getToken());
  return {
    defaultScopeId: "series",
    scopes: [
      { id: "series", title: "Series" },
      { id: "lists", title: "Reading Lists" },
      {
        id: "library",
        title: "Your Library",
        setupState: signedIn
          ? { ready: true }
          : { ready: false, message: "Sign in to search your library." },
      },
    ],
  };
}

The scopeId of the request tells you where to search:

async getSearchResults(request: SearchRequest, page: number): Promise<PagedItemList> {
  if (request.scopeId === "lists") return this.searchLists(request, page);
  if (request.scopeId === "library") return this.searchLibrary(request, page);
  return this.searchSeries(request, page);
}

Each scope can have its own filters and sort options. Write getSearchOptions(scopeId) to give them. The app calls it the first time that a person uses a scope.

async getSearchOptions(scopeId: string): Promise<SearchOptions> {
  switch (scopeId) {
    case "lists":
      return { sortOptions: { options: [{ id: "updated", title: "Recently updated" }] } };
    case "library":
      return { filters: [this.statusFilter()], sortOptions: this.librarySorts() };
    default:
      return { filters: await this.getSearchFilters(), sortOptions: await this.getSortOptions() };
  }
}

The rules for scopes

  • A request with no scopeId searches the default scope. Global search, migration and older versions of the app send no scopeId. Thus the default scope must accept a query.
  • Keep the id of each scope stable. Do not change it in a new version.
  • Keep getSearchFilters and getSortOptions. Older versions of the app use them, and they do not know about scopes. Give them the options of the default scope.
  • Make getSearchScopes fast. The app calls it each time that search opens, before it loads the options.
  • Set supportsQuery: false for a scope that has no text search. The app then hides the search field for that scope.
  • A scope with ready: false stays in the menu with its message. Also do the check again in getSearchResults.

If you write getSearchScopes and do not write getSearchOptions, the default scope uses getSearchFilters and getSortOptions. The other scopes then have no filters and no sort options.

Lists and tag pages use the filters and the sort options of the default scope.

The validation finds these errors:

  • A defaultScopeId that is not one of the scopes.
  • A default scope that does not accept a query.
  • Two scopes, filters, options or sort options with the same id.

A SearchDestination opens the search results for a request. Put it on an item or a section, for example a genre in a scope.

import { SearchDestination } from "@suwatte/toolchain";

const item: Item = {
  id: "library-all",
  title: "All Titles",
  rating: ContentRating.EVERYONE,
  destination: SearchDestination({ scopeId: "library" }, "Your Library"),
};

Older versions of the app open the link, but they search the default scope.

Search scopes and SearchDestination need toolchain 1.2.0. The app uses them in Suwatte 7.2.1 build 13 and later.