2023-01-14 16:14:54 +01:00
|
|
|
import { useState } from "react";
|
2022-02-27 20:07:15 +01:00
|
|
|
import { generatePath, useHistory, useRouteMatch } from "react-router-dom";
|
|
|
|
|
2023-04-24 17:41:54 +02:00
|
|
|
import { MWMediaType, MWQuery } from "@/backend/metadata/types";
|
|
|
|
|
2023-01-14 16:14:54 +01:00
|
|
|
function getInitialValue(params: { type: string; query: string }) {
|
|
|
|
const type =
|
|
|
|
Object.values(MWMediaType).find((v) => params.type === v) ||
|
|
|
|
MWMediaType.MOVIE;
|
2023-03-26 09:44:16 +02:00
|
|
|
const searchQuery = decodeURIComponent(params.query || "");
|
2023-01-14 16:14:54 +01:00
|
|
|
return { type, searchQuery };
|
|
|
|
}
|
|
|
|
|
2022-05-03 20:58:34 +02:00
|
|
|
export function useSearchQuery(): [
|
|
|
|
MWQuery,
|
|
|
|
(inp: Partial<MWQuery>, force: boolean) => void,
|
|
|
|
() => void
|
|
|
|
] {
|
2022-02-28 22:00:32 +01:00
|
|
|
const history = useHistory();
|
|
|
|
const { path, params } = useRouteMatch<{ type: string; query: string }>();
|
2023-01-14 16:14:54 +01:00
|
|
|
const [search, setSearch] = useState<MWQuery>(getInitialValue(params));
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2022-05-03 20:58:34 +02:00
|
|
|
const updateParams = (inp: Partial<MWQuery>, force: boolean) => {
|
2022-02-28 22:00:32 +01:00
|
|
|
const copySearch: MWQuery = { ...search };
|
2022-02-27 20:07:15 +01:00
|
|
|
Object.assign(copySearch, inp);
|
2022-05-01 23:32:33 +02:00
|
|
|
setSearch(copySearch);
|
2022-05-03 20:58:34 +02:00
|
|
|
if (!force) return;
|
2022-02-28 22:00:32 +01:00
|
|
|
history.replace(
|
|
|
|
generatePath(path, {
|
|
|
|
query:
|
|
|
|
copySearch.searchQuery.length === 0 ? undefined : inp.searchQuery,
|
|
|
|
type: copySearch.type,
|
|
|
|
})
|
|
|
|
);
|
|
|
|
};
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2022-05-03 20:58:34 +02:00
|
|
|
const onUnFocus = () => {
|
|
|
|
history.replace(
|
|
|
|
generatePath(path, {
|
|
|
|
query: search.searchQuery.length === 0 ? undefined : search.searchQuery,
|
|
|
|
type: search.type,
|
|
|
|
})
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
return [search, updateParams, onUnFocus];
|
2022-02-27 20:07:15 +01:00
|
|
|
}
|