UNPKG

nuqs

Version:

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

64 lines (63 loc) 2.35 kB
import { a as getSearchParams, i as createEmitter } from "./debounce-DPoC4s1g.js"; import { t as debug } from "./debug-CH5E3t0A.js"; import { l as error, o as globalSingleton, s as version } from "./context-Mu913OAK.js"; import { r as spinQueueResetMutex, t as resetQueues } from "./reset-DL_ZBc10.js"; //#region src/adapters/lib/patch-history.ts function getHistorySyncEmitter(adapter) { return globalSingleton(`history-emitter.${adapter}`, () => createEmitter()); } const historyUpdateMarker = "__nuqs__"; function shouldPatchHistory(adapter) { if (typeof history === "undefined") return false; if (history.nuqs?.version && history.nuqs.version !== "2.9.5") { console.error(error(409), history.nuqs.version, version, adapter); return false; } if (history.nuqs?.adapters?.includes(adapter)) return false; return true; } function markHistoryAsPatched(adapter) { history.nuqs = history.nuqs ?? { version: "2.9.5", 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, version, 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 !== "__nuqs__") sync(url); }; history.replaceState = function nuqs_replaceState(state, marker, url) { originalReplaceState.call(history, state, "", url); if (url && marker !== "__nuqs__") sync(url); }; markHistoryAsPatched(adapter); } //#endregion export { shouldPatchHistory as a, patchHistory as i, historyUpdateMarker as n, markHistoryAsPatched as r, getHistorySyncEmitter as t }; //# sourceMappingURL=patch-history-BG84kyU5.js.map