@dr.pogodin/react-global-state 0.9.3 → 0.10.0-alpha.2

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.
Files changed (55) hide show
  1. package/README.md +3 -328
  2. package/build/GlobalState.d.ts +75 -0
  3. package/build/GlobalState.js +193 -0
  4. package/build/GlobalStateProvider.d.ts +55 -0
  5. package/build/GlobalStateProvider.js +103 -0
  6. package/build/SsrContext.d.ts +6 -0
  7. package/build/SsrContext.js +10 -0
  8. package/build/index.d.ts +8 -0
  9. package/build/index.js +23 -0
  10. package/build/{module/useAsyncCollection.js → useAsyncCollection.d.ts} +16 -23
  11. package/build/useAsyncCollection.js +14 -0
  12. package/build/useAsyncData.d.ts +76 -0
  13. package/build/useAsyncData.js +150 -0
  14. package/build/{module/useGlobalState.js → useGlobalState.d.ts} +11 -62
  15. package/build/useGlobalState.js +49 -0
  16. package/build/utils.d.ts +31 -0
  17. package/build/{node/utils.js → utils.js} +11 -17
  18. package/build/withGlobalStateType.d.ts +39 -0
  19. package/build/withGlobalStateType.js +55 -0
  20. package/package.json +48 -27
  21. package/src/GlobalState.ts +279 -0
  22. package/src/GlobalStateProvider.tsx +116 -0
  23. package/src/SsrContext.ts +11 -0
  24. package/src/index.ts +33 -0
  25. package/{build/node/useAsyncCollection.js → src/useAsyncCollection.ts} +58 -25
  26. package/src/useAsyncData.ts +287 -0
  27. package/src/useGlobalState.ts +158 -0
  28. package/src/utils.ts +59 -0
  29. package/src/withGlobalStateType.ts +118 -0
  30. package/tsconfig.json +9 -0
  31. package/build/module/GlobalState.js +0 -191
  32. package/build/module/GlobalState.js.map +0 -1
  33. package/build/module/GlobalStateProvider.js +0 -81
  34. package/build/module/GlobalStateProvider.js.map +0 -1
  35. package/build/module/index.js +0 -12
  36. package/build/module/index.js.map +0 -1
  37. package/build/module/useAsyncCollection.js.map +0 -1
  38. package/build/module/useAsyncData.js +0 -206
  39. package/build/module/useAsyncData.js.map +0 -1
  40. package/build/module/useGlobalState.js.map +0 -1
  41. package/build/module/utils.js +0 -23
  42. package/build/module/utils.js.map +0 -1
  43. package/build/node/GlobalState.js +0 -174
  44. package/build/node/GlobalState.js.map +0 -1
  45. package/build/node/GlobalStateProvider.js +0 -88
  46. package/build/node/GlobalStateProvider.js.map +0 -1
  47. package/build/node/index.js +0 -56
  48. package/build/node/index.js.map +0 -1
  49. package/build/node/useAsyncCollection.js.map +0 -1
  50. package/build/node/useAsyncData.js +0 -211
  51. package/build/node/useAsyncData.js.map +0 -1
  52. package/build/node/useGlobalState.js +0 -114
  53. package/build/node/useGlobalState.js.map +0 -1
  54. package/build/node/utils.js.map +0 -1
  55. package/index.d.ts +0 -70
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ export { default as GlobalState } from './GlobalState';
2
+
3
+ export {
4
+ default as GlobalStateProvider,
5
+ getGlobalState,
6
+ getSsrContext,
7
+ } from './GlobalStateProvider';
8
+
9
+ export { default as SsrContext } from './SsrContext';
10
+
11
+ export {
12
+ type AsyncCollectionLoaderT,
13
+ default as useAsyncCollection,
14
+ } from './useAsyncCollection';
15
+
16
+ export {
17
+ type AsyncDataEnvelopeT,
18
+ type AsyncDataLoaderT,
19
+ type UseAsyncDataOptionsT,
20
+ type UseAsyncDataResT,
21
+ default as useAsyncData,
22
+ newAsyncDataEnvelope,
23
+ } from './useAsyncData';
24
+
25
+ export {
26
+ type SetterT,
27
+ type UseGlobalStateResT,
28
+ default as useGlobalState,
29
+ } from './useGlobalState';
30
+
31
+ export { type ValueOrInitializerT } from './utils';
32
+
33
+ export { default as withGlobalStateType } from './withGlobalStateType';
@@ -1,49 +1,48 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = useAsyncCollection;
8
- var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
9
1
  /**
10
2
  * Loads and uses an item in an async collection.
11
3
  */
12
4
 
5
+ import useAsyncData, {
6
+ type DataInEnvelopeAtPathT,
7
+ type UseAsyncDataOptionsT,
8
+ type UseAsyncDataResT,
9
+ } from './useAsyncData';
10
+
11
+ import { TypeLock } from './utils';
12
+
13
+ export type AsyncCollectionLoaderT<DataT> =
14
+ (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
15
+
13
16
  /**
14
17
  * Resolves and stores at the given `path` of global state elements of
15
18
  * an asynchronous data collection. In other words, it is an auxiliar wrapper
16
19
  * around {@link useAsyncData}, which uses a loader which resolves to different
17
20
  * data, based on ID argument passed in, and stores data fetched for different
18
21
  * IDs in the state.
19
- * @param {string} id ID of the collection item to load & use.
20
- * @param {string} path The global state path where entire collection should be
22
+ * @param id ID of the collection item to load & use.
23
+ * @param path The global state path where entire collection should be
21
24
  * stored.
22
- * @param {AsyncCollectionLoader} loader A loader function, which takes an
25
+ * @param loader A loader function, which takes an
23
26
  * ID of data to load, and resolves to the corresponding data.
24
- * @param {object} [options] Additional options.
25
- * @param {any[]} [options.deps=[]] An array of dependencies, which trigger
27
+ * @param options Additional options.
28
+ * @param options.deps An array of dependencies, which trigger
26
29
  * data reload when changed. Given dependency changes are watched shallowly
27
30
  * (similarly to the standard React's
28
31
  * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
29
- * @param {boolean} [options.noSSR] If `true`, this hook won't load data during
32
+ * @param options.noSSR If `true`, this hook won't load data during
30
33
  * server-side rendering.
31
- * @param {number} [options.garbageCollectAge=maxage] The maximum age of data
34
+ * @param options.garbageCollectAge The maximum age of data
32
35
  * (in milliseconds), after which they are dropped from the state when the last
33
36
  * component referencing them via `useAsyncData()` hook unmounts. Defaults to
34
37
  * `maxage` option value.
35
- * @param {number} [options.maxage=5 x 60 x 1000] The maximum age of
38
+ * @param options.maxage The maximum age of
36
39
  * data (in milliseconds) acceptable to the hook's caller. If loaded data are
37
40
  * older than this value, `null` is returned instead. Defaults to 5 minutes.
38
- * @param {number} [options.refreshAge=maxage] The maximum age of data
41
+ * @param options.refreshAge The maximum age of data
39
42
  * (in milliseconds), after which their refreshment will be triggered when
40
43
  * any component referencing them via `useAsyncData()` hook (re-)renders.
41
44
  * Defaults to `maxage` value.
42
- * @return {{
43
- * data: any,
44
- * loading: boolean,
45
- * timestamp: number
46
- * }} Returns an object with three fields: `data` holds the actual result of
45
+ * @return Returns an object with three fields: `data` holds the actual result of
47
46
  * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
48
47
  * is a boolean flag, which is `true` if data are being loaded (the hook is
49
48
  * waiting for `loader` function resolution); `timestamp` (in milliseconds)
@@ -56,8 +55,42 @@ var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
56
55
  * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
57
56
  * `useAsyncData()` hooks logic.
58
57
  */
59
- function useAsyncCollection(id, path, loader, options = {}) {
58
+
59
+ function useAsyncCollection<
60
+ StateT,
61
+ PathT extends null | string | undefined,
62
+ IdT extends string,
63
+ >(
64
+ id: IdT,
65
+ path: PathT,
66
+ loader: AsyncCollectionLoaderT<
67
+ DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>
68
+ >,
69
+ options?: UseAsyncDataOptionsT,
70
+ ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
71
+
72
+ function useAsyncCollection<
73
+ Unlocked extends 0 | 1 = 0,
74
+ DataT = unknown,
75
+ >(
76
+ id: string,
77
+ path: null | string | undefined,
78
+ loader: AsyncCollectionLoaderT<TypeLock<Unlocked, void, DataT>>,
79
+ options?: UseAsyncDataOptionsT,
80
+ ): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
81
+
82
+ function useAsyncCollection<DataT>(
83
+ id: string,
84
+ path: null | string | undefined,
85
+ loader: AsyncCollectionLoaderT<DataT>,
86
+ options: UseAsyncDataOptionsT = {},
87
+ ): UseAsyncDataResT<DataT> {
60
88
  const itemPath = path ? `${path}.${id}` : id;
61
- return (0, _useAsyncData.default)(itemPath, oldData => loader(id, oldData), options);
89
+ return useAsyncData<1, DataT>(
90
+ itemPath,
91
+ (oldData: null | DataT) => loader(id, oldData),
92
+ options,
93
+ );
62
94
  }
63
- //# sourceMappingURL=useAsyncCollection.js.map
95
+
96
+ export default useAsyncCollection;
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Loads and uses async data into the GlobalState path.
3
+ */
4
+
5
+ import { cloneDeep } from 'lodash';
6
+ import { useEffect } from 'react';
7
+ import { v4 as uuid } from 'uuid';
8
+
9
+ import { MIN_MS } from '@dr.pogodin/js-utils';
10
+
11
+ import { getGlobalState } from './GlobalStateProvider';
12
+ import useGlobalState from './useGlobalState';
13
+ import { TypeLock, isDebugMode } from './utils';
14
+
15
+ import GlobalState from './GlobalState';
16
+
17
+ import { type ValueAtPathT } from './utils';
18
+
19
+ const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
20
+
21
+ export type AsyncDataLoaderT<DataT>
22
+ = (oldData: null | DataT) => DataT | Promise<DataT>;
23
+
24
+ export type AsyncDataEnvelopeT<DataT> = {
25
+ data: null | DataT;
26
+ numRefs: number;
27
+ operationId: string;
28
+ timestamp: number;
29
+ };
30
+
31
+ export function newAsyncDataEnvelope<DataT>(
32
+ initialData: DataT | null = null,
33
+ ): AsyncDataEnvelopeT<DataT> {
34
+ return {
35
+ data: initialData,
36
+ numRefs: 0,
37
+ operationId: '',
38
+ timestamp: 0,
39
+ };
40
+ }
41
+
42
+ export type UseAsyncDataOptionsT = {
43
+ deps?: unknown[];
44
+ garbageCollectAge?: number;
45
+ maxage?: number;
46
+ noSSR?: boolean;
47
+ refreshAge?: number;
48
+ };
49
+
50
+ export type UseAsyncDataResT<DataT> = {
51
+ data: DataT | null;
52
+ loading: boolean;
53
+ timestamp: number;
54
+ };
55
+
56
+ /**
57
+ * Executes the data loading operation.
58
+ * @param path Data segment path inside the global state.
59
+ * @param loader Data loader.
60
+ * @param globalState The global state instance.
61
+ * @param oldData Optional. Previously fetched data, currently stored in
62
+ * the state, if already fetched by the caller; otherwise, they will be fetched
63
+ * by the load() function itself.
64
+ * @param opIdPrefix operationId prefix to use, which should be
65
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
66
+ * context).
67
+ * @return Resolves once the operation is done.
68
+ * @ignore
69
+ */
70
+ async function load<DataT>(
71
+ path: null | string | undefined,
72
+ loader: AsyncDataLoaderT<DataT>,
73
+ globalState: GlobalState<unknown>,
74
+ oldData: DataT | null,
75
+ opIdPrefix: 'C' | 'S' = 'C',
76
+ ): Promise<void> {
77
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
78
+ /* eslint-disable no-console */
79
+ console.log(
80
+ `ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`,
81
+ );
82
+ /* eslint-enable no-console */
83
+ }
84
+ const operationId = opIdPrefix + uuid();
85
+ const operationIdPath = path ? `${path}.operationId` : 'operationId';
86
+ globalState.set<1, string>(operationIdPath, operationId);
87
+ const data = await loader(
88
+ oldData || (globalState.get<1, AsyncDataEnvelopeT<DataT>>(path)).data,
89
+ );
90
+ const state: AsyncDataEnvelopeT<DataT> = globalState.get<1, AsyncDataEnvelopeT<DataT>>(path);
91
+ if (operationId === state.operationId) {
92
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
93
+ /* eslint-disable no-console */
94
+ console.groupCollapsed(
95
+ `ReactGlobalState: useAsyncData data (re-)loaded. Path: "${
96
+ path || ''
97
+ }"`,
98
+ );
99
+ console.log('Data:', cloneDeep(data));
100
+ /* eslint-enable no-console */
101
+ }
102
+ globalState.set<1, AsyncDataEnvelopeT<DataT>>(path, {
103
+ ...state,
104
+ data,
105
+ operationId: '',
106
+ timestamp: Date.now(),
107
+ });
108
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
109
+ /* eslint-disable no-console */
110
+ console.groupEnd();
111
+ /* eslint-enable no-console */
112
+ }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Resolves asynchronous data, and stores them at given `path` of global
118
+ * state. When multiple components rely on asynchronous data at the same `path`,
119
+ * the data are resolved once, and reused until their age is within specified
120
+ * bounds. Once the data are stale, the hook allows to refresh them. It also
121
+ * garbage-collects stale data from the global state when the last component
122
+ * relying on them is unmounted.
123
+ * @param path Dot-delimitered state path, where data envelop is
124
+ * stored.
125
+ * @param loader Asynchronous function which resolves (loads)
126
+ * data, which should be stored at the global state `path`. When multiple
127
+ * components
128
+ * use `useAsyncData()` hook for the same `path`, the library assumes that all
129
+ * hook instances are called with the same `loader` (_i.e._ whichever of these
130
+ * loaders is used to resolve async data, the result is acceptable to be reused
131
+ * in all related components).
132
+ * @param options Additional options.
133
+ * @param options.deps An array of dependencies, which trigger
134
+ * data reload when changed. Given dependency changes are watched shallowly
135
+ * (similarly to the standard React's
136
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
137
+ * @param options.noSSR If `true`, this hook won't load data during
138
+ * server-side rendering.
139
+ * @param options.garbageCollectAge The maximum age of data
140
+ * (in milliseconds), after which they are dropped from the state when the last
141
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
142
+ * `maxage` option value.
143
+ * @param options.maxage The maximum age of
144
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
145
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
146
+ * @param options.refreshAge The maximum age of data
147
+ * (in milliseconds), after which their refreshment will be triggered when
148
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
149
+ * Defaults to `maxage` value.
150
+ * @return Returns an object with three fields: `data` holds the actual result of
151
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
152
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
153
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
154
+ * is Unix timestamp of related data currently loaded into the global state.
155
+ *
156
+ * Note that loaded data, if any, are stored at the given `path` of global state
157
+ * along with related meta-information, using slightly different state segment
158
+ * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
159
+ * can be accessed, and even modified using other hooks,
160
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
161
+ * `useAsyncData()` hooks logic.
162
+ */
163
+
164
+ export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>
165
+ = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>
166
+ ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>
167
+ : void;
168
+
169
+ function useAsyncData<
170
+ StateT,
171
+ PathT extends null | string | undefined,
172
+ >(
173
+ path: PathT,
174
+ loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,
175
+ options?: UseAsyncDataOptionsT,
176
+ ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
177
+
178
+ function useAsyncData<
179
+ Unlocked extends 0 | 1 = 0,
180
+ DataT = unknown,
181
+ >(
182
+ path: null | string | undefined,
183
+ loader: AsyncDataLoaderT<TypeLock<Unlocked, void, DataT>>,
184
+ options?: UseAsyncDataOptionsT,
185
+ ): UseAsyncDataResT<TypeLock<Unlocked, void, DataT>>;
186
+
187
+ function useAsyncData<DataT>(
188
+ path: null | string | undefined,
189
+ loader: AsyncDataLoaderT<DataT>,
190
+ options: UseAsyncDataOptionsT = {},
191
+ ): UseAsyncDataResT<DataT> {
192
+ const maxage: number = options.maxage === undefined
193
+ ? DEFAULT_MAXAGE : options.maxage;
194
+
195
+ const refreshAge: number = options.refreshAge === undefined
196
+ ? maxage : options.refreshAge;
197
+
198
+ const garbageCollectAge: number = options.garbageCollectAge === undefined
199
+ ? maxage : options.garbageCollectAge;
200
+
201
+ // Note: here we can't depend on useGlobalState() to init the initial value,
202
+ // because that way we'll have issues with SSR (see details below).
203
+ const globalState = getGlobalState();
204
+ const state = globalState.get<1, AsyncDataEnvelopeT<DataT>>(path, {
205
+ initialValue: newAsyncDataEnvelope<DataT>(),
206
+ });
207
+
208
+ if (globalState.ssrContext && !options.noSSR) {
209
+ if (!state.timestamp && !state.operationId) {
210
+ globalState.ssrContext.pending.push(
211
+ load(path, loader, globalState, state.data, 'S'),
212
+ );
213
+ }
214
+ } else {
215
+ // This takes care about the client-side reference counting, and garbage
216
+ // collection.
217
+ //
218
+ // Note: the Rules of Hook below are violated by conditional call to a hook,
219
+ // but as the condition is actually server-side or client-side environment,
220
+ // it is effectively non-conditional at the runtime.
221
+ //
222
+ // TODO: Though, maybe there is a way to refactor it into a cleaner code.
223
+ // The same applies to other useEffect() hooks below.
224
+ useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
225
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
226
+ const numRefs = globalState.get<1, number>(numRefsPath);
227
+ globalState.set<1, number>(numRefsPath, numRefs + 1);
228
+ return () => {
229
+ const state2: AsyncDataEnvelopeT<DataT> = globalState.get<1, AsyncDataEnvelopeT<DataT>>(
230
+ path,
231
+ );
232
+ if (
233
+ state2.numRefs === 1
234
+ && garbageCollectAge < Date.now() - state2.timestamp
235
+ ) {
236
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
237
+ /* eslint-disable no-console */
238
+ console.log(
239
+ `ReactGlobalState - useAsyncData garbage collected at path ${
240
+ path || ''
241
+ }`,
242
+ );
243
+ /* eslint-enable no-console */
244
+ }
245
+ globalState.set<1, AsyncDataEnvelopeT<DataT>>(path, {
246
+ ...state2,
247
+ data: null,
248
+ numRefs: 0,
249
+ timestamp: 0,
250
+ });
251
+ } else globalState.set<1, number>(numRefsPath, state2.numRefs - 1);
252
+ };
253
+ }, [garbageCollectAge, globalState, path]);
254
+
255
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
256
+ // special case the otherwise wrong behavior is actually what we need.
257
+
258
+ // Data loading and refreshing.
259
+ let loadTriggered = false;
260
+ useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
261
+ const state2: AsyncDataEnvelopeT<DataT> = globalState.get<1, AsyncDataEnvelopeT<DataT>>(path);
262
+ if (refreshAge < Date.now() - state2.timestamp
263
+ && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
264
+ load(path, loader, globalState, state2.data);
265
+ loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
266
+ }
267
+ });
268
+
269
+ const deps = options.deps || [];
270
+ useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
271
+ if (!loadTriggered && deps.length) load(path, loader, globalState, null);
272
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
273
+ }
274
+
275
+ const [localState] = useGlobalState<1, AsyncDataEnvelopeT<DataT>>(
276
+ path,
277
+ newAsyncDataEnvelope<DataT>(),
278
+ );
279
+
280
+ return {
281
+ data: maxage < Date.now() - localState.timestamp ? null : localState.data,
282
+ loading: Boolean(localState.operationId),
283
+ timestamp: localState.timestamp,
284
+ };
285
+ }
286
+
287
+ export default useAsyncData;
@@ -0,0 +1,158 @@
1
+ // Hook for updates of global state.
2
+
3
+ import { cloneDeep, isFunction } from 'lodash';
4
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
5
+
6
+ import { Emitter } from '@dr.pogodin/js-utils';
7
+
8
+ import GlobalState from './GlobalState';
9
+ import { getGlobalState } from './GlobalStateProvider';
10
+
11
+ import {
12
+ type CallbackT,
13
+ type TypeLock,
14
+ type ValueAtPathT,
15
+ type ValueOrInitializerT,
16
+ isDebugMode,
17
+ } from './utils';
18
+
19
+ export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
20
+
21
+ type GlobalStateRef = {
22
+ emitter: Emitter<[]>;
23
+ globalState: GlobalState<unknown>;
24
+ path: null | string | undefined;
25
+ setter: SetterT<unknown>;
26
+ state: unknown;
27
+ watcher: CallbackT;
28
+ };
29
+
30
+ export type UseGlobalStateResT<T> = [T, SetterT<T>];
31
+
32
+ /**
33
+ * The primary hook for interacting with the global state, modeled after
34
+ * the standard React's
35
+ * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
36
+ * It subscribes a component to a given `path` of global state, and provides
37
+ * a function to update it. Each time the value at `path` changes, the hook
38
+ * triggers re-render of its host component.
39
+ *
40
+ * **Note:**
41
+ * - For performance, the library does not copy objects written to / read from
42
+ * global state paths. You MUST NOT manually mutate returned state values,
43
+ * or change objects already written into the global state, without explicitly
44
+ * clonning them first yourself.
45
+ * - State update notifications are asynchronous. When your code does multiple
46
+ * global state updates in the same React rendering cycle, all state update
47
+ * notifications are queued and dispatched together, after the current
48
+ * rendering cycle. In other words, in any given rendering cycle the global
49
+ * state values are "fixed", and all changes becomes visible at once in the
50
+ * next triggered rendering pass.
51
+ *
52
+ * @param path Dot-delimitered state path. It can be undefined to
53
+ * subscribe for entire state.
54
+ *
55
+ * Under-the-hood state values are read and written using `lodash`
56
+ * [_.get()](https://lodash.com/docs/4.17.15#get) and
57
+ * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
58
+ * to access state paths which have not been created before.
59
+ * @param initialValue Initial value to set at the `path`, or its
60
+ * factory:
61
+ * - If a function is given, it will act similar to
62
+ * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
63
+ * only if the value at `path` is `undefined`, the function will be executed,
64
+ * and the value it returns will be written to the `path`.
65
+ * - Otherwise, the given value itself will be written to the `path`,
66
+ * if the current value at `path` is `undefined`.
67
+ * @return It returs an array with two elements: `[value, setValue]`:
68
+ *
69
+ * - The `value` is the current value at given `path`.
70
+ *
71
+ * - The `setValue()` is setter function to write a new value to the `path`.
72
+ *
73
+ * Similar to the standard React's `useState()`, it supports
74
+ * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
75
+ * if `setValue()` is called with a function as argument, that function will
76
+ * be called and its return value will be written to `path`. Otherwise,
77
+ * the argument of `setValue()` itself is written to `path`.
78
+ *
79
+ * Also, similar to the standard React's state setters, `setValue()` is
80
+ * stable function: it does not change between component re-renders.
81
+ */
82
+
83
+ function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
84
+
85
+ function useGlobalState<
86
+ StateT,
87
+ PathT extends null | string | undefined,
88
+ >(
89
+ path: PathT,
90
+ initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>
91
+ ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
92
+
93
+ function useGlobalState<
94
+ Unlocked extends 0 | 1 = 0,
95
+ ValueT = void,
96
+ >(
97
+ path: null | string | undefined,
98
+ initialValue?: ValueOrInitializerT<TypeLock<Unlocked, never, ValueT>>,
99
+ ): UseGlobalStateResT<TypeLock<Unlocked, void, ValueT>>;
100
+
101
+ function useGlobalState(
102
+ path?: null | string,
103
+ initialValue?: ValueOrInitializerT<unknown>,
104
+ ): UseGlobalStateResT<any> {
105
+ const globalState = getGlobalState();
106
+
107
+ const ref = useRef<GlobalStateRef>();
108
+ const rc: GlobalStateRef = ref.current || {
109
+ emitter: new Emitter(),
110
+ globalState,
111
+ path,
112
+ setter: (value) => {
113
+ const newState = isFunction(value) ? value(rc.state) : value;
114
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
115
+ /* eslint-disable no-console */
116
+ console.groupCollapsed(
117
+ `ReactGlobalState - useGlobalState setter triggered for path ${
118
+ rc.path || ''
119
+ }`,
120
+ );
121
+ console.log('New value:', cloneDeep(newState));
122
+ console.groupEnd();
123
+ /* eslint-enable no-console */
124
+ }
125
+ rc.globalState.set<1, unknown>(rc.path, newState);
126
+ },
127
+ state: isFunction(initialValue) ? initialValue() : initialValue,
128
+ watcher: () => {
129
+ const state = rc.globalState.get(rc.path);
130
+ if (state !== rc.state) rc.emitter.emit();
131
+ },
132
+ };
133
+ ref.current = rc;
134
+
135
+ rc.globalState = globalState;
136
+ rc.path = path;
137
+
138
+ rc.state = useSyncExternalStore(
139
+ (cb) => rc.emitter.addListener(cb),
140
+ () => rc.globalState.get<1, unknown>(rc.path, { initialValue }),
141
+ () => rc.globalState.get<1, unknown>(rc.path, { initialValue, initialState: true }),
142
+ );
143
+
144
+ useEffect(() => {
145
+ const { watcher } = ref.current!;
146
+ globalState.watch(watcher);
147
+ watcher();
148
+ return () => globalState.unWatch(watcher);
149
+ }, [globalState]);
150
+
151
+ useEffect(() => {
152
+ ref.current!.watcher();
153
+ }, [path]);
154
+
155
+ return [rc.state, rc.setter];
156
+ }
157
+
158
+ export default useGlobalState;
package/src/utils.ts ADDED
@@ -0,0 +1,59 @@
1
+ import { type GetFieldType } from 'lodash';
2
+
3
+ export type CallbackT = () => void;
4
+
5
+ // TODO: This probably should be moved to JS Utils lib.
6
+ export type TypeLock<
7
+ Unlocked extends 0 | 1,
8
+ LockedT extends never | void,
9
+ UnlockedT,
10
+ > = Unlocked extends 0 ? LockedT : UnlockedT;
11
+
12
+ /**
13
+ * Given the type of state, `StateT`, and the type of state path, `PathT`,
14
+ * it evaluates the type of value at that path of the state, if it can be
15
+ * evaluated from the path type (it is possible when `PathT` is a string
16
+ * literal type, and `StateT` elements along this path have appropriate
17
+ * types); otherwise it falls back to the specified `UnknownT` type,
18
+ * which should be set either `never` (for input arguments), or `void`
19
+ * (for return types) - `never` and `void` in those places forbid assignments,
20
+ * and are not auto-inferred to more permissible types.
21
+ *
22
+ * BEWARE: When StateT is any the construct resolves to any for any string
23
+ * paths.
24
+ */
25
+ export type ValueAtPathT<
26
+ StateT,
27
+ PathT extends null | string | undefined,
28
+ UnknownT extends never | undefined | void,
29
+ > = unknown extends StateT
30
+ ? UnknownT
31
+ : string extends PathT
32
+ ? UnknownT
33
+ : PathT extends null | undefined
34
+ ? StateT
35
+ : GetFieldType<StateT, PathT> extends undefined
36
+ ? UnknownT : GetFieldType<StateT, PathT>;
37
+
38
+ export type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);
39
+
40
+ /**
41
+ * Returns 'true' if debug logging should be performed; 'false' otherwise.
42
+ *
43
+ * BEWARE: The actual safeguards for the debug logging still should read
44
+ * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
45
+ * // Some debug logging
46
+ * }
47
+ * to ensure that debug code is stripped out by Webpack in production mode.
48
+ *
49
+ * @returns
50
+ * @ignore
51
+ */
52
+ export function isDebugMode(): boolean {
53
+ try {
54
+ return process.env.NODE_ENV !== 'production'
55
+ && !!process.env.REACT_GLOBAL_STATE_DEBUG;
56
+ } catch (error) {
57
+ return false;
58
+ }
59
+ }