@dr.pogodin/react-global-state 0.10.0-alpha.1 → 0.10.0-alpha.3
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/README.md +3 -327
- package/build/common/GlobalState.js +219 -0
- package/build/common/GlobalState.js.map +1 -0
- package/build/common/GlobalStateProvider.js +101 -0
- package/build/common/GlobalStateProvider.js.map +1 -0
- package/build/common/SsrContext.js +15 -0
- package/build/common/SsrContext.js.map +1 -0
- package/build/common/index.js +76 -0
- package/build/common/index.js.map +1 -0
- package/build/common/useAsyncCollection.js +61 -0
- package/build/common/useAsyncCollection.js.map +1 -0
- package/build/common/useAsyncData.js +204 -0
- package/build/common/useAsyncData.js.map +1 -0
- package/build/common/useGlobalState.js +113 -0
- package/build/common/useGlobalState.js.map +1 -0
- package/build/common/utils.js +44 -0
- package/build/common/utils.js.map +1 -0
- package/build/common/withGlobalStateType.js +42 -0
- package/build/common/withGlobalStateType.js.map +1 -0
- package/build/module/GlobalState.js +230 -0
- package/build/module/GlobalState.js.map +1 -0
- package/build/module/GlobalStateProvider.js +94 -0
- package/build/module/GlobalStateProvider.js.map +1 -0
- package/build/module/SsrContext.js +9 -0
- package/build/module/SsrContext.js.map +1 -0
- package/build/module/index.js +8 -0
- package/build/module/index.js.map +1 -0
- package/build/module/useAsyncCollection.js +56 -0
- package/build/module/useAsyncCollection.js.map +1 -0
- package/build/module/useAsyncData.js +199 -0
- package/build/module/useAsyncData.js.map +1 -0
- package/build/module/useGlobalState.js +108 -0
- package/build/module/useGlobalState.js.map +1 -0
- package/build/module/utils.js +35 -0
- package/build/module/utils.js.map +1 -0
- package/build/module/withGlobalStateType.js +35 -0
- package/build/module/withGlobalStateType.js.map +1 -0
- package/build/types/GlobalState.d.ts +75 -0
- package/build/types/GlobalStateProvider.d.ts +55 -0
- package/build/types/SsrContext.d.ts +6 -0
- package/build/types/index.d.ts +8 -0
- package/build/types/useAsyncCollection.d.ts +51 -0
- package/build/types/useAsyncData.d.ts +75 -0
- package/build/types/useGlobalState.d.ts +58 -0
- package/build/types/utils.d.ts +34 -0
- package/build/types/withGlobalStateType.d.ts +29 -0
- package/package.json +42 -41
- package/src/GlobalState.ts +283 -0
- package/src/GlobalStateProvider.tsx +127 -0
- package/src/SsrContext.ts +11 -0
- package/src/index.ts +33 -0
- package/src/useAsyncCollection.ts +96 -0
- package/src/useAsyncData.ts +295 -0
- package/src/useGlobalState.ts +156 -0
- package/src/utils.ts +64 -0
- package/src/withGlobalStateType.ts +170 -0
- package/tsconfig.json +9 -3
- package/tsconfig.types.json +14 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses an item in an async collection.
|
|
3
|
+
*/
|
|
4
|
+
import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
5
|
+
import { type ForceT, type TypeLock } from './utils';
|
|
6
|
+
export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
|
|
7
|
+
/**
|
|
8
|
+
* Resolves and stores at the given `path` of global state elements of
|
|
9
|
+
* an asynchronous data collection. In other words, it is an auxiliar wrapper
|
|
10
|
+
* around {@link useAsyncData}, which uses a loader which resolves to different
|
|
11
|
+
* data, based on ID argument passed in, and stores data fetched for different
|
|
12
|
+
* IDs in the state.
|
|
13
|
+
* @param id ID of the collection item to load & use.
|
|
14
|
+
* @param path The global state path where entire collection should be
|
|
15
|
+
* stored.
|
|
16
|
+
* @param loader A loader function, which takes an
|
|
17
|
+
* ID of data to load, and resolves to the corresponding data.
|
|
18
|
+
* @param options Additional options.
|
|
19
|
+
* @param options.deps An array of dependencies, which trigger
|
|
20
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
21
|
+
* (similarly to the standard React's
|
|
22
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
23
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
24
|
+
* server-side rendering.
|
|
25
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
26
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
27
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
28
|
+
* `maxage` option value.
|
|
29
|
+
* @param options.maxage The maximum age of
|
|
30
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
31
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
32
|
+
* @param options.refreshAge The maximum age of data
|
|
33
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
34
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
35
|
+
* Defaults to `maxage` value.
|
|
36
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
37
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
38
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
39
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
40
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
41
|
+
*
|
|
42
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
43
|
+
* along with related meta-information, using slightly different state segment
|
|
44
|
+
* structure (see {@link AsyncDataEnvelope}). That segment of the global state
|
|
45
|
+
* can be accessed, and even modified using other hooks,
|
|
46
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
47
|
+
* `useAsyncData()` hooks logic.
|
|
48
|
+
*/
|
|
49
|
+
declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
50
|
+
declare function useAsyncCollection<Forced extends ForceT | false = false, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
51
|
+
export default useAsyncCollection;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses async data into the GlobalState path.
|
|
3
|
+
*/
|
|
4
|
+
import { type ForceT, type TypeLock, type ValueAtPathT } from './utils';
|
|
5
|
+
export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
6
|
+
export type AsyncDataEnvelopeT<DataT> = {
|
|
7
|
+
data: null | DataT;
|
|
8
|
+
numRefs: number;
|
|
9
|
+
operationId: string;
|
|
10
|
+
timestamp: number;
|
|
11
|
+
};
|
|
12
|
+
export declare function newAsyncDataEnvelope<DataT>(initialData?: DataT | null): AsyncDataEnvelopeT<DataT>;
|
|
13
|
+
export type UseAsyncDataOptionsT = {
|
|
14
|
+
deps?: unknown[];
|
|
15
|
+
garbageCollectAge?: number;
|
|
16
|
+
maxage?: number;
|
|
17
|
+
noSSR?: boolean;
|
|
18
|
+
refreshAge?: number;
|
|
19
|
+
};
|
|
20
|
+
export type UseAsyncDataResT<DataT> = {
|
|
21
|
+
data: DataT | null;
|
|
22
|
+
loading: boolean;
|
|
23
|
+
timestamp: number;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Resolves asynchronous data, and stores them at given `path` of global
|
|
27
|
+
* state. When multiple components rely on asynchronous data at the same `path`,
|
|
28
|
+
* the data are resolved once, and reused until their age is within specified
|
|
29
|
+
* bounds. Once the data are stale, the hook allows to refresh them. It also
|
|
30
|
+
* garbage-collects stale data from the global state when the last component
|
|
31
|
+
* relying on them is unmounted.
|
|
32
|
+
* @param path Dot-delimitered state path, where data envelop is
|
|
33
|
+
* stored.
|
|
34
|
+
* @param loader Asynchronous function which resolves (loads)
|
|
35
|
+
* data, which should be stored at the global state `path`. When multiple
|
|
36
|
+
* components
|
|
37
|
+
* use `useAsyncData()` hook for the same `path`, the library assumes that all
|
|
38
|
+
* hook instances are called with the same `loader` (_i.e._ whichever of these
|
|
39
|
+
* loaders is used to resolve async data, the result is acceptable to be reused
|
|
40
|
+
* in all related components).
|
|
41
|
+
* @param options Additional options.
|
|
42
|
+
* @param options.deps An array of dependencies, which trigger
|
|
43
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
44
|
+
* (similarly to the standard React's
|
|
45
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
46
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
47
|
+
* server-side rendering.
|
|
48
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
49
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
50
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
51
|
+
* `maxage` option value.
|
|
52
|
+
* @param options.maxage The maximum age of
|
|
53
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
54
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
55
|
+
* @param options.refreshAge The maximum age of data
|
|
56
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
57
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
58
|
+
* Defaults to `maxage` value.
|
|
59
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
60
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
61
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
62
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
63
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
64
|
+
*
|
|
65
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
66
|
+
* along with related meta-information, using slightly different state segment
|
|
67
|
+
* structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
|
|
68
|
+
* can be accessed, and even modified using other hooks,
|
|
69
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
70
|
+
* `useAsyncData()` hooks logic.
|
|
71
|
+
*/
|
|
72
|
+
export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
|
|
73
|
+
declare function useAsyncData<StateT, PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
74
|
+
declare function useAsyncData<Forced extends ForceT | false = false, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
75
|
+
export default useAsyncData;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
3
|
+
export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
|
|
4
|
+
export type UseGlobalStateResT<T> = [T, SetterT<T>];
|
|
5
|
+
/**
|
|
6
|
+
* The primary hook for interacting with the global state, modeled after
|
|
7
|
+
* the standard React's
|
|
8
|
+
* [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
|
|
9
|
+
* It subscribes a component to a given `path` of global state, and provides
|
|
10
|
+
* a function to update it. Each time the value at `path` changes, the hook
|
|
11
|
+
* triggers re-render of its host component.
|
|
12
|
+
*
|
|
13
|
+
* **Note:**
|
|
14
|
+
* - For performance, the library does not copy objects written to / read from
|
|
15
|
+
* global state paths. You MUST NOT manually mutate returned state values,
|
|
16
|
+
* or change objects already written into the global state, without explicitly
|
|
17
|
+
* clonning them first yourself.
|
|
18
|
+
* - State update notifications are asynchronous. When your code does multiple
|
|
19
|
+
* global state updates in the same React rendering cycle, all state update
|
|
20
|
+
* notifications are queued and dispatched together, after the current
|
|
21
|
+
* rendering cycle. In other words, in any given rendering cycle the global
|
|
22
|
+
* state values are "fixed", and all changes becomes visible at once in the
|
|
23
|
+
* next triggered rendering pass.
|
|
24
|
+
*
|
|
25
|
+
* @param path Dot-delimitered state path. It can be undefined to
|
|
26
|
+
* subscribe for entire state.
|
|
27
|
+
*
|
|
28
|
+
* Under-the-hood state values are read and written using `lodash`
|
|
29
|
+
* [_.get()](https://lodash.com/docs/4.17.15#get) and
|
|
30
|
+
* [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
|
|
31
|
+
* to access state paths which have not been created before.
|
|
32
|
+
* @param initialValue Initial value to set at the `path`, or its
|
|
33
|
+
* factory:
|
|
34
|
+
* - If a function is given, it will act similar to
|
|
35
|
+
* [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
|
|
36
|
+
* only if the value at `path` is `undefined`, the function will be executed,
|
|
37
|
+
* and the value it returns will be written to the `path`.
|
|
38
|
+
* - Otherwise, the given value itself will be written to the `path`,
|
|
39
|
+
* if the current value at `path` is `undefined`.
|
|
40
|
+
* @return It returs an array with two elements: `[value, setValue]`:
|
|
41
|
+
*
|
|
42
|
+
* - The `value` is the current value at given `path`.
|
|
43
|
+
*
|
|
44
|
+
* - The `setValue()` is setter function to write a new value to the `path`.
|
|
45
|
+
*
|
|
46
|
+
* Similar to the standard React's `useState()`, it supports
|
|
47
|
+
* [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
|
|
48
|
+
* if `setValue()` is called with a function as argument, that function will
|
|
49
|
+
* be called and its return value will be written to `path`. Otherwise,
|
|
50
|
+
* the argument of `setValue()` itself is written to `path`.
|
|
51
|
+
*
|
|
52
|
+
* Also, similar to the standard React's state setters, `setValue()` is
|
|
53
|
+
* stable function: it does not change between component re-renders.
|
|
54
|
+
*/
|
|
55
|
+
declare function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
|
|
56
|
+
declare function useGlobalState<Forced extends ForceT | false = false, ValueT = unknown>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
57
|
+
declare function useGlobalState<StateT, PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
58
|
+
export default useGlobalState;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type GetFieldType } from 'lodash';
|
|
2
|
+
export type CallbackT = () => void;
|
|
3
|
+
declare const force: unique symbol;
|
|
4
|
+
export type ForceT = typeof force;
|
|
5
|
+
export type TypeLock<Unlocked extends ForceT | false, LockedT extends never | void, UnlockedT> = Unlocked extends ForceT ? UnlockedT : LockedT;
|
|
6
|
+
/**
|
|
7
|
+
* Given the type of state, `StateT`, and the type of state path, `PathT`,
|
|
8
|
+
* it evaluates the type of value at that path of the state, if it can be
|
|
9
|
+
* evaluated from the path type (it is possible when `PathT` is a string
|
|
10
|
+
* literal type, and `StateT` elements along this path have appropriate
|
|
11
|
+
* types); otherwise it falls back to the specified `UnknownT` type,
|
|
12
|
+
* which should be set either `never` (for input arguments), or `void`
|
|
13
|
+
* (for return types) - `never` and `void` in those places forbid assignments,
|
|
14
|
+
* and are not auto-inferred to more permissible types.
|
|
15
|
+
*
|
|
16
|
+
* BEWARE: When StateT is any the construct resolves to any for any string
|
|
17
|
+
* paths.
|
|
18
|
+
*/
|
|
19
|
+
export type ValueAtPathT<StateT, PathT extends null | string | undefined, UnknownT extends never | undefined | void> = unknown extends StateT ? UnknownT : string extends PathT ? UnknownT : PathT extends null | undefined ? StateT : GetFieldType<StateT, PathT> extends undefined ? UnknownT : GetFieldType<StateT, PathT>;
|
|
20
|
+
export type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);
|
|
21
|
+
/**
|
|
22
|
+
* Returns 'true' if debug logging should be performed; 'false' otherwise.
|
|
23
|
+
*
|
|
24
|
+
* BEWARE: The actual safeguards for the debug logging still should read
|
|
25
|
+
* if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
26
|
+
* // Some debug logging
|
|
27
|
+
* }
|
|
28
|
+
* to ensure that debug code is stripped out by Webpack in production mode.
|
|
29
|
+
*
|
|
30
|
+
* @returns
|
|
31
|
+
* @ignore
|
|
32
|
+
*/
|
|
33
|
+
export declare function isDebugMode(): boolean;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
2
|
+
import GlobalStateProvider, { getGlobalState, getSsrContext } from './GlobalStateProvider';
|
|
3
|
+
import SsrContext from './SsrContext';
|
|
4
|
+
import { type UseGlobalStateResT } from './useGlobalState';
|
|
5
|
+
import { type AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
6
|
+
import { type AsyncDataLoaderT, type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
7
|
+
interface NarrowedUseGlobalStateI<StateT> {
|
|
8
|
+
(): UseGlobalStateResT<StateT>;
|
|
9
|
+
<PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
10
|
+
<Forced extends ForceT | false = false, ValueT = unknown>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
11
|
+
}
|
|
12
|
+
interface NarrowedUseAsyncDataI<StateT> {
|
|
13
|
+
<PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
14
|
+
<Forced extends ForceT | false = false, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, never, DataT>>;
|
|
15
|
+
}
|
|
16
|
+
interface NarrowedUseAsyncCollectionI<StateT> {
|
|
17
|
+
<PathT extends null | string | undefined>(id: string, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
18
|
+
<Forced extends ForceT | false = false, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
|
|
19
|
+
}
|
|
20
|
+
type WithGlobalStateTypeResT<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> = {
|
|
21
|
+
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
22
|
+
getSsrContext: typeof getSsrContext<SsrContextT>;
|
|
23
|
+
GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;
|
|
24
|
+
useAsyncCollection: NarrowedUseAsyncCollectionI<StateT>;
|
|
25
|
+
useAsyncData: NarrowedUseAsyncDataI<StateT>;
|
|
26
|
+
useGlobalState: NarrowedUseGlobalStateI<StateT>;
|
|
27
|
+
};
|
|
28
|
+
export default function withGlobalStateType<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>>(): WithGlobalStateTypeResT<StateT, SsrContextT>;
|
|
29
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.10.0-alpha.
|
|
3
|
+
"version": "0.10.0-alpha.3",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
|
-
"main": "./build/
|
|
5
|
+
"main": "./build/common/index.js",
|
|
6
6
|
"react-native": "src/index.ts",
|
|
7
7
|
"source": "src/index.ts",
|
|
8
|
+
"types": "./build/types/index.d.ts",
|
|
8
9
|
"exports": {
|
|
9
10
|
"module": "./build/module/index.js",
|
|
10
|
-
"node": "./build/
|
|
11
|
-
"
|
|
12
|
-
"default": "./build/node/index.js"
|
|
11
|
+
"node": "./build/common/index.js",
|
|
12
|
+
"default": "./build/common/index.js"
|
|
13
13
|
},
|
|
14
14
|
"scripts": {
|
|
15
|
-
"build": "rimraf build && npm run build:
|
|
16
|
-
"build:
|
|
17
|
-
"build:
|
|
15
|
+
"build": "rimraf build && npm run build:types && npm run build:common && npm run build:module",
|
|
16
|
+
"build:common": "rimraf build/common && babel src -x .ts,.tsx --out-dir build/common --source-maps",
|
|
17
|
+
"build:module": "rimraf build/module && babel src -x .ts,.tsx --out-dir build/module --source-maps --config-file ./babel.module.config.js",
|
|
18
|
+
"build:types": "rimraf build/types && tsc --project tsconfig.types.json",
|
|
18
19
|
"jest": "npm run jest:types && npm run jest:logic",
|
|
19
|
-
"jest:types": "jest --config jest/config-types.json",
|
|
20
20
|
"jest:logic": "jest --config jest/config.json -w 1",
|
|
21
|
+
"jest:types": "jest --config jest/config-types.json",
|
|
21
22
|
"lint": "eslint --ext .js,.jsx,.ts,.tsx .",
|
|
22
23
|
"test": "npm run lint && npm run typecheck && npm run jest",
|
|
23
|
-
"typecheck": "tsc --
|
|
24
|
+
"typecheck": "tsc --project __tests__/tsconfig.json"
|
|
24
25
|
},
|
|
25
26
|
"repository": "github:birdofpreyru/react-global-state",
|
|
26
27
|
"keywords": [
|
|
@@ -39,53 +40,53 @@
|
|
|
39
40
|
},
|
|
40
41
|
"homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
|
|
41
42
|
"engines": {
|
|
42
|
-
"node": ">=
|
|
43
|
+
"node": ">=18"
|
|
43
44
|
},
|
|
44
45
|
"dependencies": {
|
|
45
|
-
"@babel/runtime": "^7.
|
|
46
|
+
"@babel/runtime": "^7.23.2",
|
|
46
47
|
"@dr.pogodin/js-utils": "^0.0.6",
|
|
47
48
|
"lodash": "^4.17.21",
|
|
48
|
-
"uuid": "^9.0.
|
|
49
|
+
"uuid": "^9.0.1"
|
|
49
50
|
},
|
|
50
51
|
"devDependencies": {
|
|
51
|
-
"@babel/cli": "^7.
|
|
52
|
-
"@babel/core": "^7.
|
|
53
|
-
"@babel/eslint-parser": "^7.22.
|
|
54
|
-
"@babel/eslint-plugin": "^7.22.
|
|
55
|
-
"@babel/node": "^7.22.
|
|
56
|
-
"@babel/plugin-transform-runtime": "^7.
|
|
57
|
-
"@babel/preset-env": "^7.
|
|
58
|
-
"@babel/preset-react": "^7.22.
|
|
59
|
-
"@babel/preset-typescript": "^7.
|
|
60
|
-
"@tsconfig/recommended": "^1.0.
|
|
61
|
-
"@tsd/typescript": "^5.
|
|
62
|
-
"@types/jest": "^29.5.
|
|
63
|
-
"@types/lodash": "^4.14.
|
|
64
|
-
"@types/pretty": "^2.0.
|
|
65
|
-
"@types/react": "^18.2.
|
|
66
|
-
"@types/react-dom": "^18.2.
|
|
67
|
-
"@types/uuid": "^9.0.
|
|
68
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
69
|
-
"@typescript-eslint/parser": "^
|
|
70
|
-
"babel-jest": "^29.
|
|
52
|
+
"@babel/cli": "^7.23.0",
|
|
53
|
+
"@babel/core": "^7.23.2",
|
|
54
|
+
"@babel/eslint-parser": "^7.22.15",
|
|
55
|
+
"@babel/eslint-plugin": "^7.22.10",
|
|
56
|
+
"@babel/node": "^7.22.19",
|
|
57
|
+
"@babel/plugin-transform-runtime": "^7.23.2",
|
|
58
|
+
"@babel/preset-env": "^7.23.2",
|
|
59
|
+
"@babel/preset-react": "^7.22.15",
|
|
60
|
+
"@babel/preset-typescript": "^7.23.2",
|
|
61
|
+
"@tsconfig/recommended": "^1.0.3",
|
|
62
|
+
"@tsd/typescript": "^5.2.2",
|
|
63
|
+
"@types/jest": "^29.5.6",
|
|
64
|
+
"@types/lodash": "^4.14.200",
|
|
65
|
+
"@types/pretty": "^2.0.2",
|
|
66
|
+
"@types/react": "^18.2.31",
|
|
67
|
+
"@types/react-dom": "^18.2.14",
|
|
68
|
+
"@types/uuid": "^9.0.6",
|
|
69
|
+
"@typescript-eslint/eslint-plugin": "^6.8.0",
|
|
70
|
+
"@typescript-eslint/parser": "^6.8.0",
|
|
71
|
+
"babel-jest": "^29.7.0",
|
|
71
72
|
"babel-plugin-module-resolver": "^5.0.0",
|
|
72
|
-
"eslint": "^8.
|
|
73
|
+
"eslint": "^8.52.0",
|
|
73
74
|
"eslint-config-airbnb": "^19.0.4",
|
|
74
|
-
"eslint-config-airbnb-typescript": "^17.
|
|
75
|
+
"eslint-config-airbnb-typescript": "^17.1.0",
|
|
75
76
|
"eslint-import-resolver-babel-module": "^5.3.2",
|
|
76
|
-
"eslint-plugin-import": "^2.
|
|
77
|
-
"eslint-plugin-jest": "^27.
|
|
77
|
+
"eslint-plugin-import": "^2.28.1",
|
|
78
|
+
"eslint-plugin-jest": "^27.4.3",
|
|
78
79
|
"eslint-plugin-jsx-a11y": "^6.7.1",
|
|
79
|
-
"eslint-plugin-react": "^7.
|
|
80
|
+
"eslint-plugin-react": "^7.33.2",
|
|
80
81
|
"eslint-plugin-react-hooks": "^4.6.0",
|
|
81
|
-
"jest": "^29.
|
|
82
|
-
"jest-environment-jsdom": "^29.
|
|
82
|
+
"jest": "^29.7.0",
|
|
83
|
+
"jest-environment-jsdom": "^29.7.0",
|
|
83
84
|
"jest-runner-tsd": "^6.0.0",
|
|
84
85
|
"mockdate": "^3.0.5",
|
|
85
86
|
"pretty": "^2.0.0",
|
|
86
87
|
"rimraf": "^5.0.1",
|
|
87
88
|
"tsd-lite": "^0.8.0",
|
|
88
|
-
"typescript": "^5.
|
|
89
|
+
"typescript": "^5.2.2"
|
|
89
90
|
},
|
|
90
91
|
"peerDependencies": {
|
|
91
92
|
"react": "^18.2.0",
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cloneDeep,
|
|
3
|
+
get,
|
|
4
|
+
isFunction,
|
|
5
|
+
isObject,
|
|
6
|
+
isNil,
|
|
7
|
+
set,
|
|
8
|
+
toPath,
|
|
9
|
+
} from 'lodash';
|
|
10
|
+
|
|
11
|
+
import SsrContext from './SsrContext';
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
type CallbackT,
|
|
15
|
+
type ForceT,
|
|
16
|
+
type TypeLock,
|
|
17
|
+
type ValueAtPathT,
|
|
18
|
+
type ValueOrInitializerT,
|
|
19
|
+
isDebugMode,
|
|
20
|
+
} from './utils';
|
|
21
|
+
|
|
22
|
+
const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
|
|
23
|
+
|
|
24
|
+
type GetOptsT<T> = {
|
|
25
|
+
initialState?: boolean;
|
|
26
|
+
initialValue?: ValueOrInitializerT<T>;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export default class GlobalState<
|
|
30
|
+
StateT,
|
|
31
|
+
SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
|
|
32
|
+
> {
|
|
33
|
+
readonly ssrContext?: SsrContextT;
|
|
34
|
+
|
|
35
|
+
#initialState: StateT;
|
|
36
|
+
|
|
37
|
+
// TODO: It is tempting to replace watchers here by
|
|
38
|
+
// Emitter from @dr.pogodin/js-utils, but we need to clone
|
|
39
|
+
// current watchers for emitting later, and this is not something
|
|
40
|
+
// Emitter supports right now.
|
|
41
|
+
#watchers: CallbackT[] = [];
|
|
42
|
+
|
|
43
|
+
#nextNotifierId?: NodeJS.Timeout;
|
|
44
|
+
|
|
45
|
+
#currentState: StateT;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Creates a new global state object.
|
|
49
|
+
* @param initialState Intial global state content.
|
|
50
|
+
* @param ssrContext Server-side rendering context.
|
|
51
|
+
*/
|
|
52
|
+
constructor(
|
|
53
|
+
initialState: StateT,
|
|
54
|
+
ssrContext?: SsrContextT,
|
|
55
|
+
) {
|
|
56
|
+
this.#currentState = initialState;
|
|
57
|
+
this.#initialState = initialState;
|
|
58
|
+
|
|
59
|
+
if (ssrContext) {
|
|
60
|
+
/* eslint-disable no-param-reassign */
|
|
61
|
+
ssrContext.dirty = false;
|
|
62
|
+
ssrContext.pending = [];
|
|
63
|
+
ssrContext.state = this.#currentState;
|
|
64
|
+
/* eslint-enable no-param-reassign */
|
|
65
|
+
|
|
66
|
+
this.ssrContext = ssrContext;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
70
|
+
/* eslint-disable no-console */
|
|
71
|
+
let msg = 'New ReactGlobalState created';
|
|
72
|
+
if (ssrContext) msg += ' (SSR mode)';
|
|
73
|
+
console.groupCollapsed(msg);
|
|
74
|
+
console.log('Initial state:', cloneDeep(initialState));
|
|
75
|
+
console.groupEnd();
|
|
76
|
+
/* eslint-enable no-console */
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Gets entire state, the same way as .get(null, opts) would do.
|
|
82
|
+
* @param opts.initialState
|
|
83
|
+
* @param opts.initialValue
|
|
84
|
+
*/
|
|
85
|
+
getEntireState(opts?: GetOptsT<StateT>): StateT {
|
|
86
|
+
let state = opts?.initialState ? this.#initialState : this.#currentState;
|
|
87
|
+
if (state !== undefined || opts?.initialValue === undefined) return state;
|
|
88
|
+
|
|
89
|
+
const iv = opts.initialValue;
|
|
90
|
+
state = isFunction(iv) ? iv() : iv;
|
|
91
|
+
if (this.#currentState === undefined) this.setEntireState(state);
|
|
92
|
+
return state;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Notifies all connected state watchers that a state update has happened.
|
|
97
|
+
*/
|
|
98
|
+
private notifyStateUpdate(path: null | string | undefined, value: unknown) {
|
|
99
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
100
|
+
/* eslint-disable no-console */
|
|
101
|
+
const p = typeof path === 'string'
|
|
102
|
+
? `"${path}"` : 'none (entire state update)';
|
|
103
|
+
console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
|
|
104
|
+
console.log('New value:', cloneDeep(value));
|
|
105
|
+
console.log('New state:', cloneDeep(this.#currentState));
|
|
106
|
+
console.groupEnd();
|
|
107
|
+
/* eslint-enable no-console */
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (this.ssrContext) {
|
|
111
|
+
this.ssrContext.dirty = true;
|
|
112
|
+
this.ssrContext.state = this.#currentState;
|
|
113
|
+
} else if (!this.#nextNotifierId) {
|
|
114
|
+
this.#nextNotifierId = setTimeout(() => {
|
|
115
|
+
this.#nextNotifierId = undefined;
|
|
116
|
+
const watchers = [...this.#watchers];
|
|
117
|
+
for (let i = 0; i < watchers.length; ++i) {
|
|
118
|
+
watchers[i]();
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Sets entire state, the same way as .set(null, value) would do.
|
|
126
|
+
* @param value
|
|
127
|
+
*/
|
|
128
|
+
setEntireState(value: StateT): StateT {
|
|
129
|
+
if (this.#currentState !== value) {
|
|
130
|
+
this.#currentState = value;
|
|
131
|
+
this.notifyStateUpdate(null, value);
|
|
132
|
+
}
|
|
133
|
+
return value;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Gets current or initial value at the specified "path" of the global state.
|
|
138
|
+
* @param path Dot-delimitered state path.
|
|
139
|
+
* @param options Additional options.
|
|
140
|
+
* @param options.initialState If "true" the value will be read
|
|
141
|
+
* from the initial state instead of the current one.
|
|
142
|
+
* @param options.initialValue If the value read from the "path" is
|
|
143
|
+
* "undefined", this "initialValue" will be returned instead. In such case
|
|
144
|
+
* "initialValue" will also be written to the "path" of the current global
|
|
145
|
+
* state (no matter "initialState" flag), if "undefined" is stored there.
|
|
146
|
+
* @return Retrieved value.
|
|
147
|
+
*/
|
|
148
|
+
|
|
149
|
+
// .get() without arguments just falls back to .getEntireState().
|
|
150
|
+
get(): StateT;
|
|
151
|
+
|
|
152
|
+
// This variant attempts to automatically resolve and check the type of value
|
|
153
|
+
// at the given path, as precise as the actual state and path types permit.
|
|
154
|
+
// If the automatic path resolution is not possible, the ValueT fallsback
|
|
155
|
+
// to `never` (or to `undefined` in some cases), effectively forbidding
|
|
156
|
+
// to use this .get() variant.
|
|
157
|
+
get<
|
|
158
|
+
PathT extends null | string | undefined,
|
|
159
|
+
ValueArgT extends ValueAtPathT<StateT, PathT, never>,
|
|
160
|
+
ValueResT extends ValueAtPathT<StateT, PathT, void>,
|
|
161
|
+
>(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
|
|
162
|
+
|
|
163
|
+
// This variant is not callable by default (without generic arguments),
|
|
164
|
+
// otherwise it allows to set the correct ValueT directly.
|
|
165
|
+
get<Forced extends ForceT | false = false, ValueT = void>(
|
|
166
|
+
path?: null | string,
|
|
167
|
+
opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,
|
|
168
|
+
): TypeLock<Forced, void, ValueT>;
|
|
169
|
+
|
|
170
|
+
get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {
|
|
171
|
+
if (isNil(path)) {
|
|
172
|
+
const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);
|
|
173
|
+
return (res as unknown) as ValueT;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const state = opts?.initialState ? this.#initialState : this.#currentState;
|
|
177
|
+
|
|
178
|
+
let res = get(state, path);
|
|
179
|
+
if (res !== undefined || opts?.initialValue === undefined) return res;
|
|
180
|
+
|
|
181
|
+
const iv = opts.initialValue;
|
|
182
|
+
res = isFunction(iv) ? iv() : iv;
|
|
183
|
+
|
|
184
|
+
if (!opts?.initialState || this.get(path) === undefined) {
|
|
185
|
+
this.set<ForceT, unknown>(path, res);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return res;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Writes the `value` to given global state `path`.
|
|
193
|
+
* @param path Dot-delimitered state path. If not given, entire
|
|
194
|
+
* global state content is replaced by the `value`.
|
|
195
|
+
* @param value The value.
|
|
196
|
+
* @return Given `value` itself.
|
|
197
|
+
*/
|
|
198
|
+
|
|
199
|
+
// This variant attempts automatic value type resolution & checking.
|
|
200
|
+
set<
|
|
201
|
+
PathT extends null | string | undefined,
|
|
202
|
+
ValueArgT extends ValueAtPathT<StateT, PathT, never>,
|
|
203
|
+
ValueResT extends ValueAtPathT<StateT, PathT, void>,
|
|
204
|
+
>(path: PathT, value: ValueArgT): ValueResT;
|
|
205
|
+
|
|
206
|
+
// This variant is disabled by default, otherwise allows to give
|
|
207
|
+
// expected value type explicitly.
|
|
208
|
+
set<Forced extends ForceT | false = false, ValueT = never>(
|
|
209
|
+
path: null | string | undefined,
|
|
210
|
+
value: TypeLock<Forced, never, ValueT>,
|
|
211
|
+
): TypeLock<Forced, void, ValueT>;
|
|
212
|
+
|
|
213
|
+
set(path: null | string | undefined, value: unknown): unknown {
|
|
214
|
+
if (isNil(path)) return this.setEntireState(value as StateT);
|
|
215
|
+
|
|
216
|
+
if (value !== this.get(path)) {
|
|
217
|
+
const root = { state: this.#currentState };
|
|
218
|
+
let segIdx = 0;
|
|
219
|
+
let pos: any = root;
|
|
220
|
+
const pathSegments = toPath(`state.${path}`);
|
|
221
|
+
for (; segIdx < pathSegments.length - 1; segIdx += 1) {
|
|
222
|
+
const seg = pathSegments[segIdx];
|
|
223
|
+
const next = pos[seg];
|
|
224
|
+
if (Array.isArray(next)) pos[seg] = [...next];
|
|
225
|
+
else if (isObject(next)) pos[seg] = { ...next };
|
|
226
|
+
else {
|
|
227
|
+
// We arrived to a state sub-segment, where the remaining part of
|
|
228
|
+
// the update path does not exist yet. We rely on lodash's set()
|
|
229
|
+
// function to create the remaining path, and set the value.
|
|
230
|
+
set(pos, pathSegments.slice(segIdx), value);
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
pos = pos[seg];
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (segIdx === pathSegments.length - 1) {
|
|
237
|
+
pos[pathSegments[segIdx]] = value;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
this.#currentState = root.state;
|
|
241
|
+
|
|
242
|
+
this.notifyStateUpdate(path, value);
|
|
243
|
+
}
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Unsubscribes `callback` from watching state updates; no operation if
|
|
249
|
+
* `callback` is not subscribed to the state updates.
|
|
250
|
+
* @param callback
|
|
251
|
+
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
252
|
+
* watching functionality is intended for client-side (non-SSR) only.
|
|
253
|
+
*/
|
|
254
|
+
unWatch(callback: CallbackT) {
|
|
255
|
+
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
256
|
+
|
|
257
|
+
const watchers = this.#watchers;
|
|
258
|
+
const pos = watchers.indexOf(callback);
|
|
259
|
+
if (pos >= 0) {
|
|
260
|
+
watchers[pos] = watchers[watchers.length - 1];
|
|
261
|
+
watchers.pop();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Subscribes `callback` to watch state updates; no operation if
|
|
267
|
+
* `callback` is already subscribed to this state instance.
|
|
268
|
+
* @param callback It will be called without any arguments every
|
|
269
|
+
* time the state content changes (note, howhever, separate state updates can
|
|
270
|
+
* be applied to the state at once, and watching callbacks will be called once
|
|
271
|
+
* after such bulk update).
|
|
272
|
+
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
273
|
+
* watching functionality is intended for client-side (non-SSR) only.
|
|
274
|
+
*/
|
|
275
|
+
watch(callback: CallbackT) {
|
|
276
|
+
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
277
|
+
|
|
278
|
+
const watchers = this.#watchers;
|
|
279
|
+
if (watchers.indexOf(callback) < 0) {
|
|
280
|
+
watchers.push(callback);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|