UNPKG

nuqs

Version:

Type-safe search params state manager for React - Like useState, but stored in the URL query string

62 lines (60 loc) 2.16 kB
import { i as getSearchParams } from "./debounce-CmIkjWrj.js"; import { t as debug } from "./debug-C9V5O52N.js"; import { s as error } from "./context-CayRnDCw.js"; import { r as spinQueueResetMutex, t as resetQueues } from "./reset-B22_73QB.js"; //#region src/adapters/lib/patch-history.ts const historyUpdateMarker = "__nuqs__"; function shouldPatchHistory(adapter) { if (typeof history === "undefined") return false; if (history.nuqs?.version && history.nuqs.version !== "2.9.0") { console.error(error(409), history.nuqs.version, `2.9.0`, adapter); return false; } if (history.nuqs?.adapters?.includes(adapter)) return false; return true; } function markHistoryAsPatched(adapter) { history.nuqs = history.nuqs ?? { version: "2.9.0", adapters: [] }; history.nuqs.adapters.push(adapter); } function patchHistory(emitter, adapter) { if (!shouldPatchHistory(adapter)) return; let lastSearchSeen = typeof location === "object" ? location.search : ""; emitter.on("update", (search) => { const searchString = search.toString(); lastSearchSeen = searchString.length ? "?" + searchString : ""; }); window.addEventListener("popstate", () => { lastSearchSeen = location.search; resetQueues(); }); debug(21, "2.9.0", adapter); function sync(url) { spinQueueResetMutex(); try { if (new URL(url, location.origin).search === lastSearchSeen) return; } catch {} try { emitter.emit("update", getSearchParams(url)); } catch (e) { console.error(e); } } const originalPushState = history.pushState; const originalReplaceState = history.replaceState; history.pushState = function nuqs_pushState(state, marker, url) { originalPushState.call(history, state, "", url); if (url && marker !== historyUpdateMarker) sync(url); }; history.replaceState = function nuqs_replaceState(state, marker, url) { originalReplaceState.call(history, state, "", url); if (url && marker !== historyUpdateMarker) sync(url); }; markHistoryAsPatched(adapter); } //#endregion export { shouldPatchHistory as i, markHistoryAsPatched as n, patchHistory as r, historyUpdateMarker as t }; //# sourceMappingURL=patch-history-C6w4_G-g.js.map