nuqs
Version:
56 lines (53 loc) • 2.29 kB
JavaScript
'use client';
import { n as createAdapterProvider, o as renderQueryString } from "../context-CayRnDCw.js";
import { t as resetQueues } from "../reset-B22_73QB.js";
import { startTransition, useCallback, useEffect, useMemo, useRef } from "react";
import { useLocation, useRouter, useRouterState } from "@tanstack/react-router";
//#region src/adapters/tanstack-router.ts
function useNuqsTanstackRouterAdapter(watchKeys) {
const pathname = useLocation({ select: (state) => state.pathname });
const search = useRouterState({
select: (state) => Object.fromEntries(Object.entries(state.location.search).filter(([key]) => watchKeys.includes(key))),
structuralSharing: true
});
const resolvedPathname = useRouterState({ select: (state) => state.resolvedLocation?.pathname ?? state.location.pathname });
const router = useRouter();
const { navigate } = router;
useEffect(() => {
return router.history.subscribe(({ action }) => {
if (action.type === "BACK" || action.type === "FORWARD" || action.type === "GO") resetQueues();
});
}, [router.history]);
const ownedPathnameRef = useRef(pathname);
const cachedSearchRef = useRef(search);
const isPathStable = pathname === resolvedPathname;
if (isPathStable) {
ownedPathnameRef.current = pathname;
cachedSearchRef.current = search;
}
const activeSearch = !isPathStable && ownedPathnameRef.current !== pathname ? cachedSearchRef.current : search;
return {
searchParams: useMemo(() => new URLSearchParams(Object.entries(activeSearch).flatMap(([key, value]) => {
if (Array.isArray(value)) return value.map((v) => [key, v]);
else if (typeof value === "object" && value !== null) return [[key, JSON.stringify(value)]];
else return [[key, value]];
})), [activeSearch, watchKeys.join(",")]),
updateUrl: useCallback((search, options) => {
startTransition(() => {
navigate({
from: "/",
to: pathname + renderQueryString(search),
replace: options.history === "replace",
resetScroll: options.scroll,
hash: (prevHash) => prevHash ?? "",
state: (state) => state
});
});
}, [navigate, pathname]),
rateLimitFactor: 1
};
}
const NuqsAdapter = createAdapterProvider(useNuqsTanstackRouterAdapter);
//#endregion
export { NuqsAdapter };
//# sourceMappingURL=tanstack-router.js.map