import { useLocale } from "next-intl"; import { useParams, usePathname, useRouter, useSearchParams, } from "next/navigation"; import { parse, stringify } from "qs"; import { useCallback, useEffect, useState } from "react"; import urlcat from "urlcat"; export function useWindowArea() { const [windowLength, setWindowLength] = useState( typeof window === "object" ? window.innerWidth : 0, ); const [windowHeight, setWindowHeight] = useState( typeof window === "object" ? window.innerHeight : 0, ); useEffect(() => { const onModified = () => { setWindowLength(window.innerWidth); setWindowHeight(window.innerHeight); }; window.addEventListener("resize", onModified); return () => { window.removeEventListener("resize", onModified); }; }, []); return { windowLength, windowHeight }; } export function useTo() { const { push } = useRouter(); return useCallback( (pathname: string, search = "") => push(urlcat(pathname, parse(search))), [push], ); } export function useParam(text: string, defaultValue: string) { const to = useTo(); const searchParams = useSearchParams(); const param = searchParams.get(text) ?? defaultValue; const pathname = usePathname(); return { param, setParam: useCallback( (param: string) => { to(pathname, stringify({ ...searchParams.entries(), [text]: param })); }, [pathname, searchParams, text, to], ), }; } export function useIntParam(text: string, defaultValue: number) { const { param, setParam } = useParam(text, defaultValue.toString()); return { param: Number(param), setParam: useCallback( (param: number) => { setParam(param.toString()); }, [setParam], ), }; } export function useWant(route: string) { const to = useTo(); const { want = [] } = useParams(); return { want: want[0] ?? "", setWant: useCallback( (want: string) => { to(route + "/" + want); }, [to, route], ), }; } export function useIsPath() { const pathname = usePathname(); const locale = useLocale(); return useCallback( (route: string) => pathname.startsWith(`/${locale}${route}`), [locale, pathname], ); }