state-in-url 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants/constants.d.ts +4 -0
- package/dist/constants/index.d.ts +1 -0
- package/dist/encodeState/encodeState.d.ts +32 -0
- package/dist/encodeState/encodeState.mjs +1 -1
- package/dist/encodeState/index.d.ts +1 -0
- package/dist/encoder/encoder.d.ts +34 -0
- package/dist/encoder/encoder.mjs +1 -1
- package/dist/encoder/index.d.ts +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/next/index.d.ts +1 -0
- package/dist/next/useUrlState/index.d.ts +1 -0
- package/dist/next/useUrlState/useUrlState.d.ts +61 -0
- package/dist/next/useUrlState/useUrlState.mjs +1 -1
- package/dist/parseSPObj.d.ts +13 -0
- package/dist/parseSPObj.mjs +1 -1
- package/dist/react-router/index.d.ts +1 -0
- package/dist/react-router/useUrlState/index.d.ts +1 -0
- package/dist/react-router/useUrlState/useUrlState.d.ts +52 -0
- package/dist/react-router/useUrlState/useUrlState.mjs +1 -1
- package/dist/subscribers.d.ts +11 -0
- package/dist/useInsertionEffect.d.ts +2 -0
- package/dist/useSharedState/index.d.ts +1 -0
- package/dist/useSharedState/useSharedState.d.ts +24 -0
- package/dist/useSharedState/useSharedState.mjs +1 -1
- package/dist/useUrlEncode/index.d.ts +1 -0
- package/dist/useUrlEncode/useUrlEncode.d.ts +45 -0
- package/dist/useUrlStateBase/index.d.ts +1 -0
- package/dist/useUrlStateBase/useUrlStateBase.d.ts +42 -0
- package/dist/useUrlStateBase/useUrlStateBase.mjs +1 -1
- package/dist/utils.d.ts +28 -0
- package/dist/utils.mjs +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './constants';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type JSONCompatible, type UnknownObj } from '../utils';
|
|
2
|
+
/**
|
|
3
|
+
* Encodes the state object into a URL query string.
|
|
4
|
+
*
|
|
5
|
+
* @param {JSONCompatible<T>} state - The state object to encode.
|
|
6
|
+
* @param {JSONCompatible<T>} [defaults] - Optional default values for the state object.
|
|
7
|
+
* @return {string} The encoded URL query string representing the state object.
|
|
8
|
+
*
|
|
9
|
+
* * Example:
|
|
10
|
+
* ```ts
|
|
11
|
+
* export const form = { name: '' };
|
|
12
|
+
* encodeState({ name: 'test' }, form, 'someExistingParam=123');
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/encodeState#encodestate}
|
|
16
|
+
*/
|
|
17
|
+
export declare function encodeState<T extends JSONCompatible>(state: T, defaults?: T, paramsToKeep?: string | URLSearchParams): string;
|
|
18
|
+
/**
|
|
19
|
+
* Decodes a URI string into an object of type T.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} uriString - The URI string to decode.
|
|
22
|
+
* @return {T} The decoded object of type T.
|
|
23
|
+
*
|
|
24
|
+
* * Example:
|
|
25
|
+
* ```ts
|
|
26
|
+
* export const form = { name: '' };
|
|
27
|
+
* decodeState('key=value&name=Alex', form);
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/encodeState#decodestate}
|
|
31
|
+
*/
|
|
32
|
+
export declare function decodeState<T extends JSONCompatible>(uriString: string | URLSearchParams, defaults?: T): undefined extends T ? UnknownObj : T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{encode as t,decode as
|
|
1
|
+
import{encode as t,decode as r}from"../encoder/encoder.mjs";import{getParams as n}from"../utils.mjs";function e(r,e,o){const i=n(o);return Object.entries(r||{}).forEach((([r,n])=>{const o=e?.[r];JSON.stringify(n)!==JSON.stringify(o)&&i.set(r,t(n))})),i.toString()}function o(t,e){return{...e||{},...Object.fromEntries([...n(t).entries()].map((([t,n])=>{const o=e?.[t];return[t,r(n,o)??o]})))}}export{o as decodeState,e as encodeState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { decodeState, encodeState } from './encodeState';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type JSONCompatible } from '../utils';
|
|
2
|
+
/**
|
|
3
|
+
* Encode any JSON serializable value to URL friendly string
|
|
4
|
+
*
|
|
5
|
+
* @param {unknown} payload any value to serialize
|
|
6
|
+
* @returns {string} URLSearchParams compatible value string
|
|
7
|
+
*
|
|
8
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/encoder#encode}
|
|
9
|
+
*/
|
|
10
|
+
export declare function encode(payload: unknown): string;
|
|
11
|
+
export type Primitive = Exclude<ReturnType<typeof decodePrimitive>, typeof errorSym>;
|
|
12
|
+
/**
|
|
13
|
+
* Decode value part of URLSearchParams back to JS value
|
|
14
|
+
*
|
|
15
|
+
* @param {string} payload URLSearchParams compatible value string
|
|
16
|
+
* @param {any} fallback optional fallback value
|
|
17
|
+
* @returns {unknown} decoded object
|
|
18
|
+
*
|
|
19
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/encoder#decode}
|
|
20
|
+
*/
|
|
21
|
+
export declare function decode<T>(payload: string, fallback?: T): JSONCompatible | Primitive;
|
|
22
|
+
export declare const decodePrimitive: (str: string) => Date | typeof errorSym | undefined;
|
|
23
|
+
export declare const errorSym: unique symbol;
|
|
24
|
+
export declare const reviver: (_key: string, value: unknown) => unknown;
|
|
25
|
+
/**
|
|
26
|
+
* Parses a JSON string into a TypeScript object.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} jsonString - The JSON string to parse.
|
|
29
|
+
* @param {T} [fallbackValue] - The fallback value to use if parsing fails.
|
|
30
|
+
* @return {T | Primitive | undefined} - The parsed object or a primitive value, or undefined if parsing fails.
|
|
31
|
+
*
|
|
32
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url}
|
|
33
|
+
*/
|
|
34
|
+
export declare function parseJSON<T extends JSONCompatible>(jsonString: string, fallbackValue?: T): T | Primitive | undefined;
|
package/dist/encoder/encoder.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SYMBOLS as t}from"../constants/constants.mjs";import{typeOf as
|
|
1
|
+
import{SYMBOLS as t}from"../constants/constants.mjs";import{typeOf as e}from"../utils.mjs";function n(n){if(a(n))return n;switch(e(n)){case"function":case"symbol":return"";case"date":return r=n,t.date+new Date(r).toISOString();case"undefined":return t.undefined;default:return JSON.stringify(n).replaceAll('"',"'")}var r}function r(t,e){return o(t.replaceAll("'",'"'),e)}const s=e=>{if(e!==t.undefined)return e?.startsWith?.(t.date)?new Date(e.slice(1)):i},i=Symbol("isError"),c=(t,e)=>{const n="string"==typeof e,r=n&&s(e);return r===i?e:n?r:e};function o(t,e){try{return JSON.parse(t,c)}catch{const n=s(t);return n!==i?n:e}}const u=new RegExp(`^(${t.undefined}|${t.date})`),a=t=>u.test(String(t));export{r as decode,s as decodePrimitive,n as encode,i as errorSym,o as parseJSON,c as reviver};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { decode, encode } from './encoder';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { decode, encode } from './encoder';
|
|
2
|
+
import { decodeState, encodeState } from './encodeState';
|
|
3
|
+
import { useUrlState } from './next';
|
|
4
|
+
import { useSharedState } from './useSharedState';
|
|
5
|
+
import { useUrlEncode } from './useUrlEncode';
|
|
6
|
+
import { useUrlStateBase } from './useUrlStateBase';
|
|
7
|
+
import { isSSR, type JSONCompatible, type Type, typeOf } from './utils';
|
|
8
|
+
export { decode, decodeState, encode, encodeState, isSSR, typeOf, useSharedState, useUrlEncode, useUrlState, useUrlStateBase, };
|
|
9
|
+
export type { JSONCompatible, Type };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlState } from './useUrlState';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './useUrlState';
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { useRouter } from 'next/navigation';
|
|
2
|
+
import { type DeepReadonly, type JSONCompatible } from '../../utils';
|
|
3
|
+
/**
|
|
4
|
+
* NextJS hook. Returns `state`, `updateState`, and `updateUrl` functions
|
|
5
|
+
*
|
|
6
|
+
* @param {JSONCompatible<T>} [defaultState] Fallback (default) values for state
|
|
7
|
+
* @param {?SearchParams<T>} [searchParams] searchParams from Next server component
|
|
8
|
+
*
|
|
9
|
+
* * Example:
|
|
10
|
+
* ```ts
|
|
11
|
+
* export const form = { name: '', age: 0 };
|
|
12
|
+
* const { state, updateState, updateUrl } = useUrlState({ defaultState: form });
|
|
13
|
+
* // for nextjs seerver components
|
|
14
|
+
* // const { state, updateState, updateUrl } = useUrlState({ defaultState: form, searchParams });
|
|
15
|
+
*
|
|
16
|
+
* updateState({ name: 'test' });
|
|
17
|
+
* // by default it's uses router.push with scroll: false
|
|
18
|
+
* updateUrl({ name: 'test' }, { replace: true, scroll: true });
|
|
19
|
+
* // similar to React.useState
|
|
20
|
+
* updateUrl(curr => ({ ...curr, name: 'test' }), { replace: true, scroll: true });
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/next/useUrlState#api}
|
|
24
|
+
*/
|
|
25
|
+
export declare function useUrlState<T extends JSONCompatible>({ defaultState, searchParams, ...opts }: {
|
|
26
|
+
defaultState: T;
|
|
27
|
+
searchParams?: object;
|
|
28
|
+
replace?: boolean;
|
|
29
|
+
scroll?: boolean;
|
|
30
|
+
}): {
|
|
31
|
+
/**
|
|
32
|
+
* * Example:
|
|
33
|
+
* ```ts
|
|
34
|
+
* updateState({ name: 'test' });
|
|
35
|
+
* // or
|
|
36
|
+
* updateState(curr => ({ ...curr, name: 'test' }) );
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/next/useUrlState#updatestate}
|
|
40
|
+
*/
|
|
41
|
+
updateState: (value: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T)) => void;
|
|
42
|
+
/**
|
|
43
|
+
* * Example:
|
|
44
|
+
* ```ts
|
|
45
|
+
* updateUrl({ name: 'test' });
|
|
46
|
+
* // or
|
|
47
|
+
* updateUrl(curr => ({ ...curr, name: 'test' }), { replace: true, scroll: false } );
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/next/useUrlState#updateurl}
|
|
51
|
+
*/
|
|
52
|
+
updateUrl: (value?: Parameters<(value?: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T) | undefined, options?: import("../../useUrlStateBase/useUrlStateBase").Options) => void>[0], options?: Options) => void;
|
|
53
|
+
state: DeepReadonly<DeepReadonly<T>>;
|
|
54
|
+
getState: () => T;
|
|
55
|
+
};
|
|
56
|
+
type Router = ReturnType<typeof useRouter>;
|
|
57
|
+
type RouterOptions = NonNullable<Parameters<Router['push']>[1] | Parameters<Router['replace']>[1]>;
|
|
58
|
+
interface Options extends RouterOptions {
|
|
59
|
+
replace?: boolean;
|
|
60
|
+
}
|
|
61
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useRouter as t,useSearchParams as e}from"next/navigation";import a from"react";import{parseSPObj as r}from"../../parseSPObj.mjs";import{useUrlStateBase as s}from"../../useUrlStateBase/useUrlStateBase.mjs";import{
|
|
1
|
+
import{useRouter as t,useSearchParams as e}from"next/navigation";import a from"react";import{parseSPObj as r}from"../../parseSPObj.mjs";import{useUrlStateBase as s}from"../../useUrlStateBase/useUrlStateBase.mjs";import{isSSR as o,filterUnknownParams as m,filterUnknownParamsClient as p}from"../../utils.mjs";function u({defaultState:u,searchParams:i,...l}){const n=t(),{state:f,updateState:S,updateUrl:d,getState:j}=s(u,n,(({parse:t})=>o()?r(m(u,i),u):t(p(u)))),U=a.useCallback(((t,e)=>{const a={...c,...l,...e};d(t,a)}),[d,l]),b=e();return a.useEffect((()=>{S(m(u,r(Object.fromEntries([...b.entries()]),u)))}),[b]),{updateState:S,updateUrl:U,state:f,getState:j}}const c={replace:!0,scroll:!1};export{u as useUrlState};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type JSONCompatible } from './utils';
|
|
2
|
+
/**
|
|
3
|
+
* Parses the Next.js server-side `searchParams` into an object.
|
|
4
|
+
*
|
|
5
|
+
* Or with react-router
|
|
6
|
+
* {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/react-router/useUrlState/useUrlState.ts}
|
|
7
|
+
*
|
|
8
|
+
*
|
|
9
|
+
* @param {object | undefined} sp - The server-side searchParams object to parse.
|
|
10
|
+
* @param {T} defaults - The default values to use if parsing fails.
|
|
11
|
+
* @return {T} - The parsed object or the default values.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseSPObj<T extends JSONCompatible>(sp: object | undefined, defaults: T): T;
|
package/dist/parseSPObj.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodePrimitive as
|
|
1
|
+
import{decodePrimitive as r,errorSym as t,decode as n}from"./encoder/encoder.mjs";function e(r,t){return{...t,...o(JSON.stringify(r),t)}}function o(n,e){try{return JSON.parse(n,c)}catch{const o=r(n);return o!==t?o:e}}const c=(r,t)=>{const e="string"==typeof t,o=e&&n(t?.replaceAll?.("'",'"'));return r&&e?o:t};export{e as parseSPObj};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlState } from './useUrlState';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlState } from './useUrlState';
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type NavigateOptions } from 'react-router-dom';
|
|
2
|
+
import { type DeepReadonly, type JSONCompatible } from '../../utils';
|
|
3
|
+
/**
|
|
4
|
+
* React-router hook. Returns `state`, `updateState`, and `updateUrl` functions
|
|
5
|
+
*
|
|
6
|
+
* @param {JSONCompatible<T>} [defaultState] Fallback (default) values for state
|
|
7
|
+
* @param {NavigateOptions} [NavigateOptions] See type from `react-router-dom`
|
|
8
|
+
* * Example:
|
|
9
|
+
* ```ts
|
|
10
|
+
* export const form = { name: '', age: 0 };
|
|
11
|
+
* const { state, updateState, updateUrl } = useUrlState({ defaultState: form, replace: false, preventScrollReset: false });
|
|
12
|
+
*
|
|
13
|
+
* updateState({ name: 'test' });
|
|
14
|
+
* updateUrl({ name: 'test' }, { replace: true });
|
|
15
|
+
* // similar to React.useState
|
|
16
|
+
* updateUrl(curr => ({ ...curr, name: 'test' }), { replace: true });
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/react-router/useUrlState#api}
|
|
20
|
+
*/
|
|
21
|
+
export declare function useUrlState<T extends JSONCompatible>({ defaultState, ...initOpts }: {
|
|
22
|
+
defaultState: T;
|
|
23
|
+
} & NavigateOptions): {
|
|
24
|
+
/**
|
|
25
|
+
* * Example:
|
|
26
|
+
* ```ts
|
|
27
|
+
* updateState({ name: 'test' });
|
|
28
|
+
* // or
|
|
29
|
+
* updateState(curr => ({ ...curr, name: 'test' }) );
|
|
30
|
+
* // can pass optional React-Router `NavigateOptions`
|
|
31
|
+
* updateState(curr => ({ ...curr, name: 'test', preventScrollReset: false }) );
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/react-router/useUrlState#updatestate}
|
|
35
|
+
*/
|
|
36
|
+
updateState: (value: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T)) => void;
|
|
37
|
+
/**
|
|
38
|
+
* * Example:
|
|
39
|
+
* ```ts
|
|
40
|
+
* updateUrl({ name: 'test' });
|
|
41
|
+
* // or
|
|
42
|
+
* updateUrl(curr => ({ ...curr, name: 'test' }), { replace: true } );
|
|
43
|
+
* // can pass optional React-Router `NavigateOptions`
|
|
44
|
+
* updateState(curr => ({ ...curr, name: 'test', preventScrollReset: false }) );
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/react-router/useUrlState#updateurl}
|
|
48
|
+
*/
|
|
49
|
+
updateUrl: (value?: Parameters<(value?: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T) | undefined, options?: import("../../useUrlStateBase/useUrlStateBase").Options) => void>[0], options?: NavigateOptions) => void;
|
|
50
|
+
state: DeepReadonly<DeepReadonly<T>>;
|
|
51
|
+
getState: () => T;
|
|
52
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"react";import{useNavigate as e,useSearchParams as r}from"react-router-dom";import{parseSPObj as a}from"../../parseSPObj.mjs";import{useUrlStateBase as s}from"../../useUrlStateBase/useUrlStateBase.mjs";import{
|
|
1
|
+
import t from"react";import{useNavigate as e,useSearchParams as r}from"react-router-dom";import{parseSPObj as a}from"../../parseSPObj.mjs";import{useUrlStateBase as s}from"../../useUrlStateBase/useUrlStateBase.mjs";import{filterUnknownParamsClient as o,assignValue as m,filterUnknownParams as p}from"../../utils.mjs";function u({defaultState:u,...l}){const f=e(),i=t.useMemo((()=>({replace:(t,e)=>f(t,{...c,...l,...e}),push:(t,e)=>f(t,{...c,...l,...e})})),[f,l]),{state:n,updateState:S,updateUrl:d,getState:j}=s(u,i,(({parse:t})=>t(o(u)))),U=t.useCallback(((t,e)=>{const r={...c,...l,...e};d(t,r)}),[l]),[b]=r();return t.useEffect((()=>{S(m(u,n,p(u,a(Object.fromEntries([...b.entries()]),u))))}),[b]),{updateState:S,updateUrl:U,state:n,getState:j}}const c={replace:!0,preventScrollReset:!0};export{u as useUrlState};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type JSONCompatible } from './utils';
|
|
2
|
+
export declare const subscribers: {
|
|
3
|
+
get(obj: JSONCompatible): Cb[];
|
|
4
|
+
add(obj: JSONCompatible, cb: Cb): () => void;
|
|
5
|
+
remove(obj: JSONCompatible, cb: Cb): void;
|
|
6
|
+
};
|
|
7
|
+
export declare const stateMap: {
|
|
8
|
+
get: <T extends JSONCompatible>(objKey: T) => T;
|
|
9
|
+
set: <T extends JSONCompatible>(objKey: T, value: T) => void;
|
|
10
|
+
};
|
|
11
|
+
export type Cb = () => void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useSharedState } from './useSharedState';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type DeepReadonly, type JSONCompatible } from '../utils';
|
|
2
|
+
/**
|
|
3
|
+
* Custom React hook for sharing state between unrelated components.
|
|
4
|
+
*
|
|
5
|
+
* @param {T} defaultState - The default state object
|
|
6
|
+
* @param {() => T} [_getInitial] - Optional function to get initial state
|
|
7
|
+
* @returns {Object} Object containing `state`, `getState`, and `setState` functions
|
|
8
|
+
*
|
|
9
|
+
* * Example:
|
|
10
|
+
* ```ts
|
|
11
|
+
* export const form = { name: '', age: 0 };
|
|
12
|
+
* const { state, setState } = useSharedState(form);
|
|
13
|
+
*
|
|
14
|
+
* setState({ name: 'test' });
|
|
15
|
+
* // OR
|
|
16
|
+
* setState(curr => ({ ...curr, name: 'test' }))
|
|
17
|
+
* ```
|
|
18
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/useSharedState}
|
|
19
|
+
*/
|
|
20
|
+
export declare function useSharedState<T extends JSONCompatible>(defaultState: T, _getInitial?: () => T): {
|
|
21
|
+
state: T;
|
|
22
|
+
getState: () => T;
|
|
23
|
+
setState: (value: (Partial<T> | Partial<DeepReadonly<T>>) | ((currState: T) => T)) => void;
|
|
24
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"react";import{stateMap as r,subscribers as e}from"../subscribers.mjs";import{useInsertionEffect as n}from"../useInsertionEffect.mjs";import{isSSR as
|
|
1
|
+
import t from"react";import{stateMap as r,subscribers as e}from"../subscribers.mjs";import{useInsertionEffect as n}from"../useInsertionEffect.mjs";import{isSSR as u,isEqual as c}from"../utils.mjs";function s(s,o){const f=t.useRef(s),[a,i]=t.useState((()=>{if(u())return o?o?.():f.current;const t=r.get(f.current);if(t)return t;{const t=o?.()||f.current;return r.set(f.current,t),t}})),m=t.useCallback((t=>{const n=r.get(f.current),u="function"==typeof t?t(n):{...n,...t};c(n,u)||(r.set(f.current,u),e.get(f.current).forEach((t=>{t()})))}),[]);n((()=>{const t=e.add(f.current,(()=>{i(r.get(f.current)||f.current)}));return()=>{t()}}),[]);return{state:a,getState:t.useCallback((()=>r.get(f.current)||f.current),[]),setState:m}}export{s as useSharedState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlEncode } from './useUrlEncode';
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type JSONCompatible } from '../utils';
|
|
2
|
+
/**
|
|
3
|
+
* A hook that returns stringify and parse functions for encoding and decoding state
|
|
4
|
+
* to and from URL search parameters.
|
|
5
|
+
*
|
|
6
|
+
* @template T - The type of the state shape
|
|
7
|
+
* @param {JSONCompatible<T>} [stateShape] Fallback values for state
|
|
8
|
+
* @returns {} `stringify` and `parse` functions
|
|
9
|
+
*
|
|
10
|
+
* * Example:
|
|
11
|
+
* ```ts
|
|
12
|
+
* export const form = { name: '' };
|
|
13
|
+
* const { parse, stringify } = useUrlEncode(form);
|
|
14
|
+
*
|
|
15
|
+
* stringify({ name: 'John' }, 'someExistingParamToKeep=123');
|
|
16
|
+
* // by default it's uses router.push with scroll: false
|
|
17
|
+
* parse('name=Tom');
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/useUrlEncode#api}
|
|
21
|
+
*/
|
|
22
|
+
export declare function useUrlEncode<T extends JSONCompatible>(stateShape: T): {
|
|
23
|
+
/**
|
|
24
|
+
Parse URL query string to state object
|
|
25
|
+
* * Example:
|
|
26
|
+
* ```ts
|
|
27
|
+
const state = parse("name='Tom'");
|
|
28
|
+
console.log(state); // Output: { name: 'Tom' }
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/useUrlEncode#parse}
|
|
32
|
+
*/
|
|
33
|
+
parse: (strOrSearchParams: string | URLSearchParams) => typeof stateShape;
|
|
34
|
+
/**
|
|
35
|
+
Converts a state object to a URL query string.
|
|
36
|
+
* * Example:
|
|
37
|
+
* ```ts
|
|
38
|
+
const queryString = stringify({ name: 'John' }, 'someExistingParamToKeep=123');
|
|
39
|
+
console.log(queryString); // Output: name='John'&someExistingParamToKeep=123
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/main/packages/urlstate/useUrlEncode#stringify}
|
|
43
|
+
*/
|
|
44
|
+
stringify: (state: typeof stateShape, paramsToKeep?: string | URLSearchParams) => string;
|
|
45
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlStateBase } from './useUrlStateBase';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { useUrlEncode } from '../useUrlEncode';
|
|
2
|
+
import { type DeepReadonly, type JSONCompatible } from '../utils';
|
|
3
|
+
/**
|
|
4
|
+
* A custom React hook to create custom hooks.
|
|
5
|
+
*
|
|
6
|
+
* @template T extends JSONCompatible
|
|
7
|
+
* @param {T} defaultState - An object representing the default state values.
|
|
8
|
+
* @param {Router} router - Router object with [push] and [replace] methods.
|
|
9
|
+
* @param {Function} [getInitialState] - Optional function to get the initial state, passes `parse`, and `filterUnknownParams` helpers
|
|
10
|
+
* @returns {Object} An object containing `state`, `getState`, `updateState`, and `updateUrl` properties.
|
|
11
|
+
*
|
|
12
|
+
*
|
|
13
|
+
* * Example:
|
|
14
|
+
* ```ts
|
|
15
|
+
* export const form = { name: '' };
|
|
16
|
+
* const router = { push: () => {}, replace: () => {} };
|
|
17
|
+
* const { state, updateState, updateUrl } = useUrlStateBase(form, router, ({ parse, filterClientSP }) =>
|
|
18
|
+
* isSSR() ? getServerState() : getClientState()
|
|
19
|
+
* );
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/integrations/packages/urlstate/useUrlStateBase#api}
|
|
23
|
+
*/
|
|
24
|
+
export declare function useUrlStateBase<T extends JSONCompatible>(defaultState: T, router: Router, getInitialState?: ({ parse, }: {
|
|
25
|
+
parse: ReturnType<typeof useUrlEncode<T>>['parse'];
|
|
26
|
+
}) => T): {
|
|
27
|
+
updateState: (value: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T)) => void;
|
|
28
|
+
updateUrl: (value?: Parameters<(value: Partial<T> | Partial<DeepReadonly<T>> | ((currState: T) => T)) => void>[0], options?: Options) => void;
|
|
29
|
+
state: DeepReadonly<T>;
|
|
30
|
+
getState: () => T;
|
|
31
|
+
};
|
|
32
|
+
interface OptionsObject {
|
|
33
|
+
[key: string]: unknown;
|
|
34
|
+
}
|
|
35
|
+
export interface Options extends OptionsObject {
|
|
36
|
+
replace?: boolean;
|
|
37
|
+
}
|
|
38
|
+
type Router = {
|
|
39
|
+
push: (href: string, opts: object) => void;
|
|
40
|
+
replace: (href: string, opts: object) => void;
|
|
41
|
+
};
|
|
42
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"react";import{useInsertionEffect as e}from"../useInsertionEffect.mjs";import{useSharedState as o}from"../useSharedState/useSharedState.mjs";import{useUrlEncode as n}from"../useUrlEncode/useUrlEncode.mjs";import{filterUnknownParamsClient as a}from"../utils.mjs";function s(s,c,i){const{parse:
|
|
1
|
+
import t from"react";import{useInsertionEffect as e}from"../useInsertionEffect.mjs";import{useSharedState as o}from"../useSharedState/useSharedState.mjs";import{useUrlEncode as n}from"../useUrlEncode/useUrlEncode.mjs";import{filterUnknownParamsClient as a}from"../utils.mjs";function s(s,c,i){const{parse:m,stringify:p}=n(s),{state:w,getState:d,setState:u}=o(s,(()=>i?.({parse:m})||s));e((()=>{const t=()=>{const t=m(a(s));u(t)};return window.addEventListener(r,t),()=>{window.removeEventListener(r,t)}}),[u]);const l=t.useCallback(((t,e)=>{const o=`${window.location.pathname}${window.location.search}${window.location.hash}`,n="function"==typeof t,a=function(t){const e=Object.keys(t),o=window.location.search,n=new URLSearchParams(o),a=new URLSearchParams;return n.forEach(((t,o)=>!e.includes(o)&&a.set(o,t))),a}(s),r=n?t(d()):t?{...d(),...t}:d(),i=p(r,a);u(r);const m=`${window.location.pathname}${i.length?"?":""}${i}${window.location.hash}`;if(o!==m){const{replace:t,...o}=e||{};c[t?"replace":"push"](m,{...o})}}),[c,p,d]);return{updateState:u,updateUrl:l,state:w,getState:d}}const r="popstate";export{s as useUrlStateBase};
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type Type = 'string' | 'date' | 'boolean' | 'number' | 'bigint' | 'undefined' | 'object' | 'null' | 'function' | 'symbol' | 'array';
|
|
2
|
+
/**
|
|
3
|
+
* A better replacement for `typeof`
|
|
4
|
+
*
|
|
5
|
+
* @param {unknown} val value to detect type
|
|
6
|
+
* @returns {Type} Type of val - `string`, `date`, `boolean`,
|
|
7
|
+
* `number`, `bigint`, `undefined`, `null`, `object`,
|
|
8
|
+
* `function`, `symbol`, `array`
|
|
9
|
+
*/
|
|
10
|
+
export declare const typeOf: (val: unknown) => Type;
|
|
11
|
+
export declare const isSSR: () => boolean;
|
|
12
|
+
export type JSON = null | boolean | Date | number | string | {
|
|
13
|
+
[prop: string]: JSON | JSON[];
|
|
14
|
+
};
|
|
15
|
+
export type JSONCompatible = {
|
|
16
|
+
[prop: string]: JSON | JSON[];
|
|
17
|
+
};
|
|
18
|
+
export type DeepReadonly<T> = T extends Map<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends Set<infer S> ? ReadonlySet<DeepReadonly<S>> : T extends object ? {
|
|
19
|
+
readonly [K in keyof T]: DeepReadonly<T[K]>;
|
|
20
|
+
} : T;
|
|
21
|
+
export declare const getParams: (strOrSearchParams?: string | URLSearchParams) => URLSearchParams;
|
|
22
|
+
export type UnknownObj = object | {
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
};
|
|
25
|
+
export declare const isEqual: (val1: unknown, val2: unknown) => boolean;
|
|
26
|
+
export declare function filterUnknownParamsClient<T extends object>(shape: T): string;
|
|
27
|
+
export declare function filterUnknownParams<T extends object>(shape: T, searchParams?: object): T;
|
|
28
|
+
export declare function assignValue<T extends object>(shape: T, curr: Partial<T>, newVal: Partial<T>): T;
|
package/dist/utils.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const t=t=>{const n=typeof t,e=null===t,r=Array.isArray(t),c=t instanceof Date;return(e?"null":c&&"date")||r&&"array"||!e&&!c&&!r&&"object"===n&&"object"||n},n=()=>"undefined"==typeof window,e=t=>new URLSearchParams("string"==typeof t?r(t):t?.toString?.()||""),r=t=>t.split("?")?.[1]||t||"",c=(t,n)=>JSON.stringify(t)===JSON.stringify(n);function o(t){const n=new URLSearchParams;return s(t,[...new URLSearchParams(window.location.search).entries()]).forEach((([t,e])=>n.set(t,e))),n.toString()}function i(t,n){return Object.fromEntries(s(t,Object.entries(n||{})))}function s(t,n){const e=Object.keys(t);return n.filter((([t])=>e.includes(t))).map((([t,n])=>[t.replaceAll("+"," "),n]))}function a(t,n,e){const r=Object.assign({},t,n);return Object.entries(t).forEach((([n])=>{const c=n,o=void 0!==e[c];r[c]=o?e[c]:t[c]})),r}export{a as assignValue,i as filterUnknownParams,o as filterUnknownParamsClient,e as getParams,c as isEqual,n as isSSR,t as typeOf};
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "state-in-url",
|
|
3
|
-
"version": "3.0.
|
|
4
|
-
"description": "Library to store complex state in browser URL, includes hook for NextJS, hook for pure React, and low level helpers.
|
|
5
|
-
"homepage": "https://
|
|
3
|
+
"version": "3.0.1",
|
|
4
|
+
"description": "Library to store complex state in browser URL, includes hook for NextJS, hook for pure React, and low level helpers.",
|
|
5
|
+
"homepage": "https://state-in-url-asmyshlyaev177.vercel.app",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"front-end",
|
|
8
8
|
"state-management",
|
|
@@ -348,8 +348,8 @@
|
|
|
348
348
|
"@commitlint/config-conventional": "^19.0.3",
|
|
349
349
|
"@playwright/test": "^1.45.3",
|
|
350
350
|
"@rollup/plugin-node-resolve": "^15.3.0",
|
|
351
|
-
"@rollup/plugin-sucrase": "^5.0.2",
|
|
352
351
|
"@rollup/plugin-terser": "^0.4.4",
|
|
352
|
+
"@rollup/plugin-typescript": "^12.1.0",
|
|
353
353
|
"@semantic-release/changelog": "^6.0.3",
|
|
354
354
|
"@semantic-release/commit-analyzer": "^13.0.0",
|
|
355
355
|
"@semantic-release/git": "^10.0.1",
|
|
@@ -382,7 +382,7 @@
|
|
|
382
382
|
"playwright": "^1.45.3",
|
|
383
383
|
"prettier": "^3.2.5",
|
|
384
384
|
"release-it": "^17.6.0",
|
|
385
|
-
"rollup": "^
|
|
385
|
+
"rollup": "^4.23.0",
|
|
386
386
|
"rollup-plugin-filesize": "^10.0.0",
|
|
387
387
|
"rollup-plugin-sourcemaps": "^0.6.3",
|
|
388
388
|
"semantic-release": "^24.1.0",
|