pstream is dead; long live pstream
taciturnaxolotl.github.io/pstream-ng/
1import { useEffect, useState } from "react";
2import { generatePath, useNavigate, useParams } from "react-router-dom";
3
4function decode(query: string | null | undefined) {
5 return query ? decodeURIComponent(query) : "";
6}
7
8export function useSearchQuery(): [
9 string,
10 (inp: string, force?: boolean) => void,
11 () => void,
12] {
13 const navigate = useNavigate();
14 const params = useParams<{ query: string }>();
15 const [search, setSearch] = useState(decode(params.query));
16
17 useEffect(() => {
18 setSearch(decode(params.query));
19 }, [params.query]);
20
21 const updateParams = (inp: string, commitToUrl = false) => {
22 setSearch(inp);
23 if (!commitToUrl) return;
24 const current = decode(params.query);
25 if (inp === current) return;
26 if (inp.length === 0) {
27 navigate("/", { replace: true });
28 return;
29 }
30 navigate(
31 generatePath("/browse/:query", {
32 query: encodeURIComponent(inp),
33 }),
34 { replace: true },
35 );
36 };
37
38 const onUnFocus = (newSearch?: string) => {
39 updateParams(newSearch ?? search, true);
40 };
41
42 return [search, updateParams, onUnFocus];
43}