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) • 1.18 kB
JavaScript
;var n=require("../constants/constants.js");var u=require("../utils.js");const O=/['"]/g;const p={"'":"%27",'"':"'"};const v=/'|%27/g;const y={"'":'"',"%27":"'"};const g=new RegExp(`^(${n.SYMBOLS.undefined}|${n.SYMBOLS.date})`);function m(e){if(typeof e==="function"||typeof e==="symbol")return"";if(B(e)){return e}return JSON.stringify(e,c).replace(O,r=>p[r])}function c(e,r){const t=u.typeOf(r);if(t!=="object"&&t!=="array"){return d(r)}if(t==="object"){const i=r;const o={};for(const s of Object.keys(i)){o[s]=c(e,i[s])}return o}if(t==="array"){return r.map(i=>c(e,i))}return r}const d=e=>{switch(u.typeOf(e)){case"date":return n.SYMBOLS.date+new Date(e).toISOString();case"undefined":return n.SYMBOLS.undefined;default:return e}};function l(e,r){return f(e.replace(v,t=>y[t]),r)}function f(e,r){try{return JSON.parse(e,a)}catch{return r}}function a(e,r){return typeof r==="string"?S(r):r}const S=e=>{if(e===n.SYMBOLS.undefined)return void 0;if(e?.startsWith?.(n.SYMBOLS.date))return new Date(e.slice(1));return e};const B=e=>g.test(String(e));exports.decode=l;exports.decodePrimitive=S;exports.encode=m;exports.encodePrimitive=d;exports.parseJSON=f;exports.reviver=a;