nuqs
Version:
76 lines (75 loc) • 2.96 kB
JavaScript
import { r as globalThrottleQueue } from "./debounce-DPoC4s1g.js";
import { t as debug } from "./debug-CH5E3t0A.js";
import { c as renderQueryString } from "./context-Mu913OAK.js";
import { n as setQueueResetMutex, r as spinQueueResetMutex, t as resetQueues } from "./reset-DL_ZBc10.js";
import { a as shouldPatchHistory, n as historyUpdateMarker, r as markHistoryAsPatched } from "./patch-history-BG84kyU5.js";
import { startTransition, useCallback, useEffect, useOptimistic, useRef } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation.js";
//#region src/adapters/next/impl.app.ts
const NUM_HISTORY_CALLS_PER_UPDATE = 3;
function onPopState() {
setQueueResetMutex(0);
resetQueues();
}
function onHistoryStateUpdate() {
spinQueueResetMutex(() => {
queueMicrotask(resetQueues);
});
}
function patchHistory() {
if (!shouldPatchHistory("next/app")) return;
const originalReplaceState = history.replaceState;
const originalPushState = history.pushState;
history.replaceState = function nuqs_replaceState(state, marker, url) {
return originalReplaceState.call(history, state, marker === "__nuqs__" ? "" : marker, url);
};
history.pushState = function nuqs_pushState(state, marker, url) {
if (marker !== "__nuqs__") onHistoryStateUpdate();
return originalPushState.call(history, state, marker === "__nuqs__" ? "" : marker, url);
};
markHistoryAsPatched("next/app");
}
function NavigationSpy() {
const pathname = usePathname();
const prevPathname = useRef(pathname);
if (prevPathname.current !== pathname) {
prevPathname.current = pathname;
globalThrottleQueue.reset();
}
useEffect(() => {
patchHistory();
window.addEventListener("popstate", onPopState);
return () => window.removeEventListener("popstate", onPopState);
}, []);
return null;
}
function useNuqsNextAppRouterAdapter() {
const router = useRouter();
const pathname = usePathname();
const [optimisticSearchParams, setOptimisticSearchParams] = useOptimistic(useSearchParams() ?? new URLSearchParams());
return {
searchParams: optimisticSearchParams,
pathname,
updateUrl: useCallback((search, options) => {
startTransition(() => {
if (!options.shallow) setOptimisticSearchParams(search);
const url = renderURL(search);
debug(20, "next/app", url);
const updateMethod = options.history === "push" ? history.pushState : history.replaceState;
setQueueResetMutex(0);
updateMethod.call(history, null, historyUpdateMarker, url);
if (options.scroll) window.scrollTo(0, 0);
if (!options.shallow) router.replace(url, { scroll: false });
});
}, []),
rateLimitFactor: NUM_HISTORY_CALLS_PER_UPDATE,
autoResetQueueOnUpdate: false
};
}
function renderURL(search) {
const { origin, pathname, hash } = location;
return origin + pathname + renderQueryString(search) + hash;
}
//#endregion
export { useNuqsNextAppRouterAdapter as n, NavigationSpy as t };
//# sourceMappingURL=impl.app-C0Tb8jcf.js.map