2023-10-13 21:41:44 +02:00
|
|
|
import { useEffect, useState } from "react";
|
2023-12-23 06:24:43 +01:00
|
|
|
import { generatePath, useNavigate, useParams } from "react-router-dom";
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2023-11-29 18:30:35 +01:00
|
|
|
function decode(query: string | null | undefined) {
|
|
|
|
return query ? decodeURIComponent(query) : "";
|
|
|
|
}
|
|
|
|
|
2022-05-03 20:58:34 +02:00
|
|
|
export function useSearchQuery(): [
|
2023-10-13 21:41:44 +02:00
|
|
|
string,
|
|
|
|
(inp: string, force?: boolean) => void,
|
2023-12-23 06:24:43 +01:00
|
|
|
() => void,
|
2022-05-03 20:58:34 +02:00
|
|
|
] {
|
2023-12-23 06:24:43 +01:00
|
|
|
const navigate = useNavigate();
|
2023-07-23 12:34:59 +02:00
|
|
|
const params = useParams<{ query: string }>();
|
2023-11-29 18:30:35 +01:00
|
|
|
const [search, setSearch] = useState(decode(params.query));
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2023-10-13 21:41:44 +02:00
|
|
|
useEffect(() => {
|
2023-11-29 18:30:35 +01:00
|
|
|
setSearch(decode(params.query));
|
2023-10-13 21:41:44 +02:00
|
|
|
}, [params.query]);
|
|
|
|
|
|
|
|
const updateParams = (inp: string, commitToUrl = false) => {
|
|
|
|
setSearch(inp);
|
|
|
|
if (!commitToUrl) return;
|
|
|
|
if (inp.length === 0) {
|
2023-12-23 06:24:43 +01:00
|
|
|
navigate("/", { replace: true });
|
2023-07-23 12:34:59 +02:00
|
|
|
return;
|
|
|
|
}
|
2023-12-23 06:24:43 +01:00
|
|
|
navigate(
|
2023-07-23 12:34:59 +02:00
|
|
|
generatePath("/browse/:query", {
|
2023-10-13 21:41:44 +02:00
|
|
|
query: inp,
|
2023-12-23 06:24:43 +01:00
|
|
|
}),
|
|
|
|
{ replace: true },
|
2022-02-28 22:00:32 +01:00
|
|
|
);
|
|
|
|
};
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2022-05-03 20:58:34 +02:00
|
|
|
const onUnFocus = () => {
|
2023-10-13 21:41:44 +02:00
|
|
|
updateParams(search, true);
|
2022-05-03 20:58:34 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
return [search, updateParams, onUnFocus];
|
2022-02-27 20:07:15 +01:00
|
|
|
}
|