summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/components/Search.tsx
blob: c0dde3bef8159af2f65976978ffded3a6aa04723 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { FunctionComponent, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Autocomplete, ComboboxItem, OptionsFilter, Text } from "@mantine/core";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { chain, includes } from "lodash";
import { useServerSearch } from "@/apis/hooks";
import { useDebouncedValue } from "@/utilities";

type SearchResultItem = {
  value: string;
  link: string;
};

function useSearch(query: string) {
  const debouncedQuery = useDebouncedValue(query, 500);
  const { data } = useServerSearch(debouncedQuery, debouncedQuery.length >= 0);

  const duplicates = chain(data)
    .groupBy((item) => `${item.title} (${item.year})`)
    .filter((group) => group.length > 1)
    .map((group) => `${group[0].title} (${group[0].year})`)
    .value();

  return useMemo<SearchResultItem[]>(
    () =>
      data?.map((v) => {
        const { link, displayName } = (() => {
          const hasDuplicate = includes(duplicates, `${v.title} (${v.year})`);

          if (v.sonarrSeriesId) {
            return {
              link: `/series/${v.sonarrSeriesId}`,
              displayName: hasDuplicate
                ? `${v.title} (${v.year}) (S)`
                : `${v.title} (${v.year})`,
            };
          }

          if (v.radarrId) {
            return {
              link: `/movies/${v.radarrId}`,
              displayName: hasDuplicate
                ? `${v.title} (${v.year}) (M)`
                : `${v.title} (${v.year})`,
            };
          }

          throw new Error("Unknown search result");
        })();

        return {
          value: displayName,
          link,
        };
      }) ?? [],
    [data, duplicates],
  );
}

const optionsFilter: OptionsFilter = ({ options, search }) => {
  const lowercaseSearch = search.toLowerCase();
  const trimmedSearch = search.trim();

  return (options as ComboboxItem[]).filter((option) => {
    return (
      option.value.toLowerCase().includes(lowercaseSearch) ||
      option.value
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .toLowerCase()
        .includes(trimmedSearch)
    );
  });
};

const Search: FunctionComponent = () => {
  const navigate = useNavigate();
  const [query, setQuery] = useState("");

  const results = useSearch(query);

  return (
    <Autocomplete
      leftSection={<FontAwesomeIcon icon={faSearch} />}
      renderOption={(input) => <Text p="xs">{input.option.value}</Text>}
      placeholder="Search"
      size="sm"
      data={results}
      value={query}
      scrollAreaProps={{ type: "auto" }}
      maxDropdownHeight={400}
      onChange={setQuery}
      onBlur={() => setQuery("")}
      filter={optionsFilter}
      onOptionSubmit={(option) =>
        navigate(results.find((a) => a.value === option)?.link || "/")
      }
    ></Autocomplete>
  );
};

export default Search;