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-16, react-router@6-7, remix@2, and Astro.
2 lines (1 loc) • 1.21 kB
JavaScript
import{SYMBOLS as r}from"../constants/constants.mjs";import{typeOf as u}from"../utils.mjs";const m=/['"]/g;const O={"'":"%27",'"':"'"};const l=/'|%27/g;const v={"'":'"',"%27":"'"};function g(t){if(typeof t==="function"||typeof t==="symbol")return"";return JSON.stringify(i("",t)).replace(m,e=>O[e])}function i(t,e){const n=u(e);if(n!=="object"&&n!=="array"){return a(e)}if(n==="object"){const o=e;const c={};for(const s of Object.keys(o)){c[s]=i(t,o[s])}return c}if(n==="array"){return e.map(o=>i(t,o))}return e}const f=t=>Object.values(r).some(e=>t.startsWith(e));const a=t=>{if(typeof t==="string"&&f(t)){return r.escape+t}switch(u(t)){case"date":return r.date+new Date(t).toISOString();case"undefined":return r.undefined;default:return t}};function S(t,e){return d(t.replace(l,n=>v[n]),e)}function d(t,e){try{return JSON.parse(t,p)}catch{return e}}function p(t,e){return typeof e==="string"?y(e):e}const y=t=>{const e=t?.startsWith?.(r.escape)?t.slice(r.escape.length):void 0;if(e!==void 0&&f(e))return e;if(t===r.undefined)return void 0;if(t?.startsWith?.(r.date))return new Date(t.slice(1));return t};export{S as decode,y as decodePrimitive,g as encode,a as encodePrimitive,d as parseJSON,p as reviver};