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
|
import { useServerSearch } from "@/apis/hooks";
import { useDebouncedValue } from "@/utilities";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Anchor,
Autocomplete,
createStyles,
SelectItemProps,
} from "@mantine/core";
import { forwardRef, FunctionComponent, useMemo, useState } from "react";
import { Link } from "react-router-dom";
type SearchResultItem = {
value: string;
link: string;
};
function useSearch(query: string) {
const debouncedQuery = useDebouncedValue(query, 500);
const { data } = useServerSearch(debouncedQuery, debouncedQuery.length > 0);
return useMemo<SearchResultItem[]>(
() =>
data?.map((v) => {
let link: string;
if (v.sonarrSeriesId) {
link = `/series/${v.sonarrSeriesId}`;
} else if (v.radarrId) {
link = `/movies/${v.radarrId}`;
} else {
throw new Error("Unknown search result");
}
return {
value: `${v.title} (${v.year})`,
link,
};
}) ?? [],
[data],
);
}
const useStyles = createStyles((theme) => {
return {
result: {
color:
theme.colorScheme === "light"
? theme.colors.dark[8]
: theme.colors.gray[1],
},
};
});
type ResultCompProps = SelectItemProps & SearchResultItem;
const ResultComponent = forwardRef<HTMLDivElement, ResultCompProps>(
({ link, value }, ref) => {
const styles = useStyles();
return (
<Anchor
component={Link}
to={link}
underline={false}
className={styles.classes.result}
p="sm"
>
{value}
</Anchor>
);
},
);
const Search: FunctionComponent = () => {
const [query, setQuery] = useState("");
const results = useSearch(query);
return (
<Autocomplete
icon={<FontAwesomeIcon icon={faSearch} />}
itemComponent={ResultComponent}
placeholder="Search"
size="sm"
data={results}
value={query}
onChange={setQuery}
onBlur={() => setQuery("")}
filter={(value, item) =>
item.value.toLowerCase().includes(value.toLowerCase().trim()) ||
item.value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.includes(value.trim())
}
></Autocomplete>
);
};
export default Search;
|