UNPKG

state-in-url

Version:

Store state in URL as in object, types and structure are preserved, with TS validation. Same API as React.useState, wthout any hasssle or boilerplate. Next.js@14-15, react-router@6-7, and remix@2.

2 lines (1 loc) 2.01 kB
"use strict";const i=n=>{if(n===null)return"null";const t=typeof n;if(t!=="object")return t;if(Array.isArray(n))return"array";if(n instanceof Date)return"date";return"object"};const u=n=>{const t=i(n);return t!=="object"&&t!=="array"};const a=typeof window==="undefined";const l=n=>{if(n instanceof URLSearchParams){return n}if(typeof n==="string"){const t=n.indexOf("?");return new URLSearchParams(t===-1?n:n.slice(t+1))}return new URLSearchParams};const y=(n,t)=>{if(n.length!==t.length)return false;return n.every((r,s)=>c(r,t[s]))};const w=(n,t)=>{const r=Object.keys(n);const s=Object.keys(t);if(r.length!==s.length)return false;return r.every(e=>c(n[e],t[e]))};const c=(n,t)=>{if(n===t)return true;if(n==null||t==null)return false;const r=i(n);const s=i(t);if(r!==s)return false;if(u(n))return false;if(r==="array"){return y(n,t)}if(r==="object"){return w(n,t)}return JSON.stringify(n)===JSON.stringify(t)};function p(n,t){const r=new URLSearchParams;const s=f(n,[...new URLSearchParams(t||"").entries()]);for(const[e,o]of s){r.set(e,o)}return r.toString()}function g(n,t){return Object.fromEntries(f(n,Object.entries(t||{})))}function f(n,t){const r=Object.keys(n);const s=[];for(let e=0;e<t.length;e++){if(r.includes(t[e]?.[0])){s.push([t[e][0].replace(/\+/g," "),t[e][1]])}}return s}function h(n,t){const r=Object.assign({},n);for(const[s]of Object.entries(n)){const e=s;const o=t[e]!==void 0;r[e]=o?t[e]:n[e]}return r}const S={push:n=>{if(typeof window!=="undefined"){window.history.pushState(null,"",n)}},replace:n=>{if(typeof window!=="undefined"){window.history.replaceState(null,"",n)}}};const d=/apple/i.test(!a&&navigator?.userAgent||"");const m="popstate";function P(){return a?"":window.location.search}exports.assignValue=h;exports.filterUnknown=f;exports.filterUnknownParams=g;exports.filterUnknownParamsClient=p;exports.getParams=l;exports.getSearch=P;exports.isEqual=c;exports.isPrimitive=u;exports.isSSR=a;exports.isSafari=d;exports.popstateEv=m;exports.routerHistory=S;exports.typeOf=i;