@dr.pogodin/react-global-state 0.18.0 → 0.19.0

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 (57) hide show
  1. package/LICENSE.md +1 -1
  2. package/build/{module → code}/GlobalState.js +15 -5
  3. package/build/code/GlobalState.js.map +1 -0
  4. package/build/{module → code}/GlobalStateProvider.js +18 -18
  5. package/build/code/GlobalStateProvider.js.map +1 -0
  6. package/build/code/SsrContext.js.map +1 -0
  7. package/build/{module → code}/index.js +9 -3
  8. package/build/code/index.js.map +1 -0
  9. package/build/{module → code}/useAsyncCollection.js +60 -27
  10. package/build/code/useAsyncCollection.js.map +1 -0
  11. package/build/{module → code}/useAsyncData.js +19 -17
  12. package/build/code/useAsyncData.js.map +1 -0
  13. package/build/{module → code}/useGlobalState.js +25 -8
  14. package/build/code/useGlobalState.js.map +1 -0
  15. package/build/{module → code}/utils.js +1 -1
  16. package/build/code/utils.js.map +1 -0
  17. package/build/types/GlobalState.d.ts +2 -2
  18. package/build/types/GlobalStateProvider.d.ts +3 -3
  19. package/build/types/SsrContext.d.ts +3 -3
  20. package/build/types/useAsyncCollection.d.ts +4 -6
  21. package/build/types/useAsyncData.d.ts +2 -2
  22. package/build/types/utils.d.ts +2 -3
  23. package/eslint.config.mjs +19 -0
  24. package/package.json +25 -41
  25. package/build/common/GlobalState.js +0 -279
  26. package/build/common/GlobalState.js.map +0 -1
  27. package/build/common/GlobalStateProvider.js +0 -97
  28. package/build/common/GlobalStateProvider.js.map +0 -1
  29. package/build/common/SsrContext.js +0 -15
  30. package/build/common/SsrContext.js.map +0 -1
  31. package/build/common/index.js +0 -84
  32. package/build/common/index.js.map +0 -1
  33. package/build/common/useAsyncCollection.js +0 -242
  34. package/build/common/useAsyncCollection.js.map +0 -1
  35. package/build/common/useAsyncData.js +0 -233
  36. package/build/common/useAsyncData.js.map +0 -1
  37. package/build/common/useGlobalState.js +0 -134
  38. package/build/common/useGlobalState.js.map +0 -1
  39. package/build/common/utils.js +0 -91
  40. package/build/common/utils.js.map +0 -1
  41. package/build/module/GlobalState.js.map +0 -1
  42. package/build/module/GlobalStateProvider.js.map +0 -1
  43. package/build/module/SsrContext.js.map +0 -1
  44. package/build/module/index.js.map +0 -1
  45. package/build/module/useAsyncCollection.js.map +0 -1
  46. package/build/module/useAsyncData.js.map +0 -1
  47. package/build/module/useGlobalState.js.map +0 -1
  48. package/build/module/utils.js.map +0 -1
  49. package/src/GlobalState.ts +0 -342
  50. package/src/GlobalStateProvider.tsx +0 -117
  51. package/src/SsrContext.ts +0 -11
  52. package/src/index.ts +0 -84
  53. package/src/useAsyncCollection.ts +0 -471
  54. package/src/useAsyncData.ts +0 -362
  55. package/src/useGlobalState.ts +0 -225
  56. package/src/utils.ts +0 -116
  57. /package/build/{module → code}/SsrContext.js +0 -0
@@ -1,342 +0,0 @@
1
- import {
2
- get,
3
- isFunction,
4
- isObject,
5
- isNil,
6
- set,
7
- toPath,
8
- } from 'lodash';
9
-
10
- import SsrContext from './SsrContext';
11
-
12
- import {
13
- type CallbackT,
14
- type ForceT,
15
- type LockT,
16
- type TypeLock,
17
- type ValueAtPathT,
18
- type ValueOrInitializerT,
19
- cloneDeepForLog,
20
- isDebugMode,
21
- } from './utils';
22
-
23
- const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
24
-
25
- type GetOptsT<T> = {
26
- initialState?: boolean;
27
- initialValue?: ValueOrInitializerT<T>;
28
- };
29
-
30
- export default class GlobalState<
31
- StateT,
32
- SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
33
- > {
34
- readonly ssrContext?: SsrContextT;
35
-
36
- #asyncDataAbortCallbacks: Record<string, () => void> = {};
37
-
38
- #dependencies: { [key: string]: Readonly<any[]> } = {};
39
-
40
- #initialState: StateT;
41
-
42
- // TODO: It is tempting to replace watchers here by
43
- // Emitter from @dr.pogodin/js-utils, but we need to clone
44
- // current watchers for emitting later, and this is not something
45
- // Emitter supports right now.
46
- #watchers: CallbackT[] = [];
47
-
48
- #nextNotifierId?: NodeJS.Timeout;
49
-
50
- #currentState: StateT;
51
-
52
- /**
53
- * Creates a new global state object.
54
- * @param initialState Intial global state content.
55
- * @param ssrContext Server-side rendering context.
56
- */
57
- constructor(
58
- initialState: StateT,
59
- ssrContext?: SsrContextT,
60
- ) {
61
- this.#currentState = initialState;
62
- this.#initialState = initialState;
63
-
64
- if (ssrContext) {
65
- /* eslint-disable no-param-reassign */
66
- ssrContext.dirty = false;
67
- ssrContext.pending = [];
68
- ssrContext.state = this.#currentState;
69
- /* eslint-enable no-param-reassign */
70
-
71
- this.ssrContext = ssrContext;
72
- }
73
-
74
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
75
- /* eslint-disable no-console */
76
- let msg = 'New ReactGlobalState created';
77
- if (ssrContext) msg += ' (SSR mode)';
78
- console.groupCollapsed(msg);
79
- console.log('Initial state:', cloneDeepForLog(initialState));
80
- console.groupEnd();
81
- /* eslint-enable no-console */
82
- }
83
- }
84
-
85
- /**
86
- * Returns the number of currently registered async data abort callbacks,
87
- * just for the sake of testing the library.
88
- */
89
- get numAsyncDataAbortCallbacks(): number {
90
- return Object.keys(this.#asyncDataAbortCallbacks).length;
91
- }
92
-
93
- /**
94
- * If `aborted` is "true" and there is an abort callback registered for
95
- * the specified operation, it triggers the callback. Then, in any case,
96
- * it drops the callback.
97
- */
98
- asyncDataLoadDone(opid: string, aborted: boolean) {
99
- if (aborted) this.#asyncDataAbortCallbacks[opid]?.();
100
- delete this.#asyncDataAbortCallbacks[opid];
101
- }
102
-
103
- /**
104
- * Drops the record of dependencies, if any, for the given path.
105
- */
106
- dropDependencies(path: string) {
107
- delete this.#dependencies[path];
108
- }
109
-
110
- /**
111
- * Checks if given `deps` are different from previously recorded ones for
112
- * the given `path`. If they are, `deps` are recorded as the new deps for
113
- * the `path`, and also the array is frozen, to prevent it from being
114
- * modified.
115
- *
116
- * TODO: This may not work as expected if path string is not normalized,
117
- * and the for the same path different alternative ways to spell it down
118
- * are used. We should normalize given path here, I guess, or on a higher
119
- * level in the logic?
120
- */
121
- hasChangedDependencies(path: string, deps: any[]): boolean {
122
- const prevDeps = this.#dependencies[path];
123
- let changed = !prevDeps || prevDeps.length !== deps.length;
124
- for (let i = 0; !changed && i < deps.length; ++i) {
125
- changed = prevDeps![i] !== deps[i];
126
- }
127
- this.#dependencies[path] = Object.freeze(deps);
128
- return changed;
129
- }
130
-
131
- /**
132
- * Gets entire state, the same way as .get(null, opts) would do.
133
- * @param opts.initialState
134
- * @param opts.initialValue
135
- */
136
- getEntireState(opts?: GetOptsT<StateT>): StateT {
137
- let state = opts?.initialState ? this.#initialState : this.#currentState;
138
- if (state !== undefined || opts?.initialValue === undefined) return state;
139
-
140
- const iv = opts.initialValue;
141
- state = isFunction(iv) ? iv() : iv;
142
- if (this.#currentState === undefined) this.setEntireState(state);
143
- return state;
144
- }
145
-
146
- /**
147
- * Notifies all connected state watchers that a state update has happened.
148
- */
149
- private notifyStateUpdate(path: null | string | undefined, value: unknown) {
150
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
151
- /* eslint-disable no-console */
152
- const p = typeof path === 'string'
153
- ? `"${path}"` : 'none (entire state update)';
154
- console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
155
- console.log('New value:', cloneDeepForLog(value, path ?? ''));
156
- console.log('New state:', cloneDeepForLog(this.#currentState));
157
- console.groupEnd();
158
- /* eslint-enable no-console */
159
- }
160
-
161
- if (this.ssrContext) {
162
- this.ssrContext.dirty = true;
163
- this.ssrContext.state = this.#currentState;
164
- } else if (!this.#nextNotifierId) {
165
- this.#nextNotifierId = setTimeout(() => {
166
- this.#nextNotifierId = undefined;
167
- const watchers = [...this.#watchers];
168
- for (let i = 0; i < watchers.length; ++i) {
169
- watchers[i]!();
170
- }
171
- });
172
- }
173
- }
174
-
175
- /**
176
- * Registers an abort callback for an async data retrieval operation with
177
- * the given operation ID. Throws if already registered.
178
- */
179
- setAsyncDataAbortCallback(opid: string, cb: () => void) {
180
- this.#asyncDataAbortCallbacks[opid] = cb;
181
- }
182
-
183
- /**
184
- * Sets entire state, the same way as .set(null, value) would do.
185
- * @param value
186
- */
187
- setEntireState(value: StateT): StateT {
188
- if (this.#currentState !== value) {
189
- this.#currentState = value;
190
- this.notifyStateUpdate(null, value);
191
- }
192
- return value;
193
- }
194
-
195
- /**
196
- * Gets current or initial value at the specified "path" of the global state.
197
- * @param path Dot-delimitered state path.
198
- * @param options Additional options.
199
- * @param options.initialState If "true" the value will be read
200
- * from the initial state instead of the current one.
201
- * @param options.initialValue If the value read from the "path" is
202
- * "undefined", this "initialValue" will be returned instead. In such case
203
- * "initialValue" will also be written to the "path" of the current global
204
- * state (no matter "initialState" flag), if "undefined" is stored there.
205
- * @return Retrieved value.
206
- */
207
-
208
- // .get() without arguments just falls back to .getEntireState().
209
- get(): StateT;
210
-
211
- // This variant attempts to automatically resolve and check the type of value
212
- // at the given path, as precise as the actual state and path types permit.
213
- // If the automatic path resolution is not possible, the ValueT fallsback
214
- // to `never` (or to `undefined` in some cases), effectively forbidding
215
- // to use this .get() variant.
216
- get<
217
- PathT extends null | string | undefined,
218
- ValueArgT extends ValueAtPathT<StateT, PathT, never>,
219
- ValueResT extends ValueAtPathT<StateT, PathT, void>,
220
- >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
221
-
222
- // This variant is not callable by default (without generic arguments),
223
- // otherwise it allows to set the correct ValueT directly.
224
- get<Forced extends ForceT | LockT = LockT, ValueT = void>(
225
- path?: null | string,
226
- opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,
227
- ): TypeLock<Forced, void, ValueT>;
228
-
229
- get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {
230
- if (isNil(path)) {
231
- const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);
232
- return (res as unknown) as ValueT;
233
- }
234
-
235
- const state = opts?.initialState ? this.#initialState : this.#currentState;
236
-
237
- let res = get(state, path);
238
- if (res !== undefined || opts?.initialValue === undefined) return res;
239
-
240
- const iv = opts.initialValue;
241
- res = isFunction(iv) ? iv() : iv;
242
-
243
- if (!opts?.initialState || this.get(path) === undefined) {
244
- this.set<ForceT, unknown>(path, res);
245
- }
246
-
247
- return res;
248
- }
249
-
250
- /**
251
- * Writes the `value` to given global state `path`.
252
- * @param path Dot-delimitered state path. If not given, entire
253
- * global state content is replaced by the `value`.
254
- * @param value The value.
255
- * @return Given `value` itself.
256
- */
257
-
258
- // This variant attempts automatic value type resolution & checking.
259
- set<
260
- PathT extends null | string | undefined,
261
- ValueArgT extends ValueAtPathT<StateT, PathT, never>,
262
- ValueResT extends ValueAtPathT<StateT, PathT, void>,
263
- >(path: PathT, value: ValueArgT): ValueResT;
264
-
265
- // This variant is disabled by default, otherwise allows to give
266
- // expected value type explicitly.
267
- set<Forced extends ForceT | LockT = LockT, ValueT = never>(
268
- path: null | string | undefined,
269
- value: TypeLock<Forced, never, ValueT>,
270
- ): TypeLock<Forced, void, ValueT>;
271
-
272
- set(path: null | string | undefined, value: unknown): unknown {
273
- if (isNil(path)) return this.setEntireState(value as StateT);
274
-
275
- if (value !== this.get(path)) {
276
- const root = { state: this.#currentState };
277
- let segIdx = 0;
278
- let pos: any = root;
279
- const pathSegments = toPath(`state.${path}`);
280
- for (; segIdx < pathSegments.length - 1; segIdx += 1) {
281
- const seg = pathSegments[segIdx]!;
282
- const next = pos[seg];
283
- if (Array.isArray(next)) pos[seg] = [...next];
284
- else if (isObject(next)) pos[seg] = { ...next };
285
- else {
286
- // We arrived to a state sub-segment, where the remaining part of
287
- // the update path does not exist yet. We rely on lodash's set()
288
- // function to create the remaining path, and set the value.
289
- set(pos, pathSegments.slice(segIdx), value);
290
- break;
291
- }
292
- pos = pos[seg];
293
- }
294
-
295
- if (segIdx === pathSegments.length - 1) {
296
- pos[pathSegments[segIdx]!] = value;
297
- }
298
-
299
- this.#currentState = root.state;
300
-
301
- this.notifyStateUpdate(path, value);
302
- }
303
- return value;
304
- }
305
-
306
- /**
307
- * Unsubscribes `callback` from watching state updates; no operation if
308
- * `callback` is not subscribed to the state updates.
309
- * @param callback
310
- * @throws if {@link SsrContext} is attached to the state instance: the state
311
- * watching functionality is intended for client-side (non-SSR) only.
312
- */
313
- unWatch(callback: CallbackT) {
314
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
315
-
316
- const watchers = this.#watchers;
317
- const pos = watchers.indexOf(callback);
318
- if (pos >= 0) {
319
- watchers[pos] = watchers[watchers.length - 1]!;
320
- watchers.pop();
321
- }
322
- }
323
-
324
- /**
325
- * Subscribes `callback` to watch state updates; no operation if
326
- * `callback` is already subscribed to this state instance.
327
- * @param callback It will be called without any arguments every
328
- * time the state content changes (note, howhever, separate state updates can
329
- * be applied to the state at once, and watching callbacks will be called once
330
- * after such bulk update).
331
- * @throws if {@link SsrContext} is attached to the state instance: the state
332
- * watching functionality is intended for client-side (non-SSR) only.
333
- */
334
- watch(callback: CallbackT) {
335
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
336
-
337
- const watchers = this.#watchers;
338
- if (watchers.indexOf(callback) < 0) {
339
- watchers.push(callback);
340
- }
341
- }
342
- }
@@ -1,117 +0,0 @@
1
- import { isFunction } from 'lodash';
2
-
3
- import {
4
- type ReactNode,
5
- createContext,
6
- use,
7
- useRef,
8
- } from 'react';
9
-
10
- import GlobalState from './GlobalState';
11
- import SsrContext from './SsrContext';
12
-
13
- import { type ValueOrInitializerT } from './utils';
14
-
15
- const Context = createContext<GlobalState<unknown> | null>(null);
16
-
17
- /**
18
- * Gets {@link GlobalState} instance from the context. In most cases
19
- * you should use {@link useGlobalState}, and other hooks to interact with
20
- * the global state, instead of accessing it directly.
21
- * @return
22
- */
23
- export function getGlobalState<
24
- StateT,
25
- SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
26
- >(): GlobalState<StateT, SsrContextT> {
27
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
28
- // convention that hook names should start with use... This is intentional in
29
- // our case, as getGlobalState() hook is intended for advance scenarious,
30
- // while the normal interaction with the global state should happen via
31
- // another hook, useGlobalState().
32
- /* eslint-disable react-hooks/rules-of-hooks */
33
- const globalState = use(Context);
34
- /* eslint-enable react-hooks/rules-of-hooks */
35
- if (!globalState) throw new Error('Missing GlobalStateProvider');
36
- return globalState as GlobalState<StateT, SsrContextT>;
37
- }
38
-
39
- /**
40
- * @category Hooks
41
- * @desc Gets SSR context.
42
- * @param throwWithoutSsrContext If `true` (default),
43
- * this hook will throw if no SSR context is attached to the global state;
44
- * set `false` to not throw in such case. In either case the hook will throw
45
- * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
46
- * @returns SSR context.
47
- * @throws
48
- * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
49
- * in the rendered React tree.
50
- * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
51
- * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
52
- */
53
- export function getSsrContext<
54
- SsrContextT extends SsrContext<unknown>,
55
- >(
56
- throwWithoutSsrContext = true,
57
- ): SsrContextT | undefined {
58
- const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();
59
- if (!ssrContext && throwWithoutSsrContext) {
60
- throw new Error('No SSR context found');
61
- }
62
- return ssrContext;
63
- }
64
-
65
- type NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {
66
- initialState: ValueOrInitializerT<StateT>,
67
- ssrContext?: SsrContextT;
68
- };
69
-
70
- type GlobalStateProviderProps<
71
- StateT,
72
- SsrContextT extends SsrContext<StateT>,
73
- > = {
74
- children?: ReactNode;
75
- } & (NewStateProps<StateT, SsrContextT> | {
76
- stateProxy: true | GlobalState<StateT, SsrContextT>;
77
- });
78
-
79
- /**
80
- * Provides global state to its children.
81
- * @param prop.children Component children, which will be provided with
82
- * the global state, and rendered in place of the provider.
83
- * @param prop.initialState Initial content of the global state.
84
- * @param prop.ssrContext Server-side rendering (SSR) context.
85
- * @param prop.stateProxy This option is useful for code
86
- * splitting and SSR implementation:
87
- * - If `true`, this provider instance will fetch and reuse the global state
88
- * from a parent provider.
89
- * - If `GlobalState` instance, it will be used by this provider.
90
- * - If not given, a new `GlobalState` instance will be created and used.
91
- */
92
- const GlobalStateProvider = <
93
- StateT,
94
- SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
95
- >({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {
96
- const state = useRef<GlobalState<StateT, SsrContextT>>(undefined);
97
- if (!state.current) {
98
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
99
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
100
- // is given, we want to follow the second branch, which creates a new
101
- // GlobalState with whatever intiialState given.
102
- if ('stateProxy' in rest && rest.stateProxy) {
103
- if (rest.stateProxy === true) state.current = getGlobalState();
104
- else state.current = rest.stateProxy;
105
- } else {
106
- const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;
107
-
108
- state.current = new GlobalState<StateT, SsrContextT>(
109
- isFunction(initialState) ? initialState() : initialState,
110
- ssrContext,
111
- );
112
- }
113
- }
114
- return <Context value={state.current}>{children}</Context>;
115
- };
116
-
117
- export default GlobalStateProvider;
package/src/SsrContext.ts DELETED
@@ -1,11 +0,0 @@
1
- export default class SsrContext<StateT> {
2
- dirty: boolean = false;
3
-
4
- pending: Promise<void>[] = [];
5
-
6
- state?: StateT;
7
-
8
- constructor(state?: StateT) {
9
- this.state = state;
10
- }
11
- }
package/src/index.ts DELETED
@@ -1,84 +0,0 @@
1
- import GlobalState from './GlobalState';
2
-
3
- import GlobalStateProvider, {
4
- getGlobalState,
5
- getSsrContext,
6
- } from './GlobalStateProvider';
7
-
8
- import SsrContext from './SsrContext';
9
-
10
- import useAsyncCollection, {
11
- type UseAsyncCollectionI,
12
- type UseAsyncCollectionResT,
13
- } from './useAsyncCollection';
14
-
15
- import {
16
- type AsyncDataEnvelopeT,
17
- type AsyncDataLoaderT,
18
- type AsyncDataReloaderT,
19
- type UseAsyncDataI,
20
- type UseAsyncDataOptionsT,
21
- type UseAsyncDataResT,
22
- newAsyncDataEnvelope,
23
- useAsyncData,
24
- } from './useAsyncData';
25
-
26
- import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
27
-
28
- export type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';
29
-
30
- export type { SetterT, UseGlobalStateResT } from './useGlobalState';
31
-
32
- export type { ForceT, ValueOrInitializerT } from './utils';
33
-
34
- export {
35
- type AsyncDataEnvelopeT,
36
- type AsyncDataLoaderT,
37
- type AsyncDataReloaderT,
38
- type UseAsyncCollectionResT,
39
- type UseAsyncDataOptionsT,
40
- type UseAsyncDataResT,
41
- getGlobalState,
42
- getSsrContext,
43
- GlobalState,
44
- GlobalStateProvider,
45
- newAsyncDataEnvelope,
46
- SsrContext,
47
- useAsyncCollection,
48
- useAsyncData,
49
- useGlobalState,
50
- };
51
-
52
- interface API<
53
- StateT,
54
- SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
55
- > {
56
- getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
57
- getSsrContext: typeof getSsrContext<SsrContextT>,
58
- GlobalState: typeof GlobalState<StateT, SsrContextT>,
59
- GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,
60
- newAsyncDataEnvelope: typeof newAsyncDataEnvelope,
61
- SsrContext: typeof SsrContext<StateT>,
62
- useAsyncCollection: UseAsyncCollectionI<StateT>,
63
- useAsyncData: UseAsyncDataI<StateT>,
64
- useGlobalState: UseGlobalStateI<StateT>,
65
- }
66
-
67
- const api = {
68
- getGlobalState,
69
- getSsrContext,
70
- GlobalState,
71
- GlobalStateProvider,
72
- newAsyncDataEnvelope,
73
- SsrContext,
74
- useAsyncCollection,
75
- useAsyncData,
76
- useGlobalState,
77
- };
78
-
79
- export function withGlobalStateType<
80
- StateT,
81
- SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
82
- >() {
83
- return api as API<StateT, SsrContextT>;
84
- }