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 and react-router@6-7.

2 lines (1 loc) 1.06 kB
import{SYMBOLS as n}from"../constants/constants.mjs";import{typeOf as u}from"../utils.mjs";function p(e){if(typeof e==="function"||typeof e==="symbol")return"";if(l(e)){return e}return JSON.stringify(structuredClone(e),o).replace(/'/g,"%27").replace(/"/g,"'")}function o(e,r){const i=u(r);if(i!=="object"&&i!=="array"){return f(r)}if(i==="object"){const t=r;for(const c of Object.keys(t)){t[c]=o(e,t[c])}return t}if(i==="array"){return r.map(t=>o(e,t))}return r}const f=e=>{switch(u(e)){case"date":return n.date+new Date(e).toISOString();case"undefined":return n.undefined;default:return e}};function y(e,r){return a(e.replace(/'/g,'"').replace(/%27/g,"'"),r)}function a(e,r){try{return JSON.parse(e,s)}catch{return r}}function s(e,r){return typeof r==="string"?d(r):r}const d=e=>{if(e===n.undefined)return void 0;if(e?.startsWith?.(n.date))return new Date(e.slice(1));return e};const g=new RegExp(`^(${n.undefined}|${n.date})`);const l=e=>g.test(String(e));export{y as decode,d as decodePrimitive,p as encode,f as encodePrimitive,a as parseJSON,s as reviver};