@dr.pogodin/react-global-state 0.20.1 → 0.21.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.
@@ -1,283 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = void 0;
8
- var _react = require("react");
9
- var _uuid = require("uuid");
10
- var _GlobalStateProvider = require("./GlobalStateProvider");
11
- var _useAsyncData = require("./useAsyncData");
12
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
13
- var _utils = require("./utils");
14
- /**
15
- * Loads and uses item(s) in an async collection.
16
- */
17
-
18
- /**
19
- * GarbageCollector: the piece of logic executed on mounting of
20
- * an useAsyncCollection() hook, and on update of hook params, to update
21
- * the state according to the new param values. It increments by 1 `numRefs`
22
- * counters for the requested collection items.
23
- */
24
- function gcOnWithhold(ids, path, gs) {
25
- const collection = {
26
- ...gs.get(path)
27
- };
28
- for (const id of ids) {
29
- let envelope = collection[id];
30
- if (envelope) envelope = {
31
- ...envelope,
32
- numRefs: 1 + envelope.numRefs
33
- };else envelope = (0, _useAsyncData.newAsyncDataEnvelope)(null, {
34
- numRefs: 1
35
- });
36
- collection[id] = envelope;
37
- }
38
- gs.set(path, collection);
39
- }
40
- function idsToStringSet(ids) {
41
- const res = new Set();
42
- for (const id of ids) {
43
- res.add(id.toString());
44
- }
45
- return res;
46
- }
47
-
48
- /**
49
- * GarbageCollector: the piece of logic executed on un-mounting of
50
- * an useAsyncCollection() hook, and on update of hook params, to clean-up
51
- * after the previous param values. It decrements by 1 `numRefs` counters
52
- * for previously requested collection items, and also drops from the state
53
- * stale records.
54
- */
55
- function gcOnRelease(ids, path, gs, gcAge) {
56
- const entries = Object.entries(gs.get(path));
57
- const now = Date.now();
58
- const idSet = idsToStringSet(ids);
59
- const collection = {};
60
- for (const [id, envelope] of entries) {
61
- if (envelope) {
62
- const toBeReleased = idSet.has(id);
63
- let {
64
- numRefs
65
- } = envelope;
66
- if (toBeReleased) --numRefs;
67
- if (gcAge > now - envelope.timestamp || numRefs > 0) {
68
- collection[id] = toBeReleased ? {
69
- ...envelope,
70
- numRefs
71
- } : envelope;
72
- } else if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
73
- // eslint-disable-next-line no-console
74
- console.log(`useAsyncCollection(): Garbage collected at the path "${path}", ID = ${id}`);
75
- }
76
- }
77
- }
78
- gs.set(path, collection);
79
- }
80
- function normalizeIds(idOrIds) {
81
- if (Array.isArray(idOrIds)) {
82
- // Removes ID duplicates.
83
- const res = Array.from(new Set(idOrIds));
84
-
85
- // Ensures stable ID order.
86
- res.sort((a, b) => a.toString().localeCompare(b.toString()));
87
- return res;
88
- }
89
- return [idOrIds];
90
- }
91
-
92
- /**
93
- * Resolves and stores at the given `path` of the global state elements of
94
- * an asynchronous data collection.
95
- */
96
-
97
- // TODO: This is largely similar to useAsyncData() logic, just more generic.
98
- // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
99
- // and reused in both hooks.
100
- // eslint-disable-next-line complexity
101
- function useAsyncCollection(idOrIds, path, loader, options = {}) {
102
- const ids = normalizeIds(idOrIds);
103
- const maxage = options.maxage ?? _useAsyncData.DEFAULT_MAXAGE;
104
- const refreshAge = options.refreshAge ?? maxage;
105
- const garbageCollectAge = options.garbageCollectAge ?? maxage;
106
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
107
-
108
- // Server-side logic.
109
- if (globalState.ssrContext) {
110
- if (!options.disabled && !options.noSSR) {
111
- const operationId = `S${(0, _uuid.v4)()}`;
112
- for (const id of ids) {
113
- const itemPath = path ? `${path}.${id}` : `${id}`;
114
- const state = globalState.get(itemPath, {
115
- initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
116
- });
117
- if (!state.timestamp && !state.operationId) {
118
- const promiseOrVoid = (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
119
- data: state.data,
120
- timestamp: state.timestamp
121
- }, operationId);
122
- if (promiseOrVoid instanceof Promise) {
123
- globalState.ssrContext.pending.push(promiseOrVoid);
124
- }
125
- }
126
- }
127
- }
128
-
129
- // Client-side logic.
130
- } else {
131
- const {
132
- disabled
133
- } = options;
134
-
135
- // Reference-counting & garbage collection.
136
-
137
- const idsHash = (0, _utils.hash)(ids);
138
-
139
- // TODO: Violation of rules of hooks is fine here,
140
- // but perhaps it can be refactored to avoid the need for it.
141
- (0, _react.useEffect)(() => {
142
- // eslint-disable-line react-hooks/rules-of-hooks
143
- if (!disabled) gcOnWithhold(ids, path, globalState);
144
- return () => {
145
- if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);
146
- };
147
-
148
- // `ids` are represented in the dependencies array by `idsHash` value,
149
- // as useEffect() hook requires a constant size of dependencies array.
150
- // eslint-disable-next-line react-hooks/exhaustive-deps
151
- }, [disabled, garbageCollectAge, globalState, idsHash, path]);
152
-
153
- // NOTE: a bunch of Rules of Hooks ignored belows because in our very
154
- // special case the otherwise wrong behavior is actually what we need.
155
-
156
- // Data loading and refreshing.
157
- (0, _react.useEffect)(() => {
158
- // eslint-disable-line react-hooks/rules-of-hooks
159
- if (!disabled) {
160
- void (async () => {
161
- for (const id of ids) {
162
- const itemPath = path ? `${path}.${id}` : `${id}`;
163
- const state2 = globalState.get(itemPath);
164
- const {
165
- deps
166
- } = options;
167
- if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
168
- if (!deps) globalState.dropDependencies(itemPath);
169
- await (0, _useAsyncData.load)(itemPath,
170
- // TODO: I guess, the loader is not correctly typed here -
171
- // it can be synchronous, and in that case the following method
172
- // should be kept synchronous to not alter the sync logic.
173
- // eslint-disable-next-line @typescript-eslint/promise-function-async
174
- (old, ...args) => loader(id, old, ...args), globalState, {
175
- data: state2?.data,
176
- timestamp: state2?.timestamp ?? 0
177
- });
178
- }
179
- }
180
- })();
181
- }
182
- });
183
- }
184
- const [localState] = (0, _useGlobalState.default)(path, {});
185
- const ref = (0, _react.useRef)(null);
186
- ref.current ??= {
187
- globalState,
188
- ids,
189
- loader,
190
- path
191
- };
192
- (0, _react.useEffect)(() => {
193
- ref.current = {
194
- globalState,
195
- ids,
196
- loader,
197
- path
198
- };
199
- }, [globalState, ids, loader, path]);
200
- const [stable] = (0, _react.useState)(() => {
201
- const reload = async customLoader => {
202
- const rc = ref.current;
203
- if (!rc) throw Error('Internal error');
204
- const localLoader = customLoader ?? rc.loader;
205
-
206
- // TODO: Revise - not sure all related typing is 100% correct,
207
- // thus let's keep this runtime assertion.
208
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
209
- if (!localLoader || !rc.globalState || !rc.ids) {
210
- throw Error('Internal error');
211
- }
212
- for (const id of rc.ids) {
213
- const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;
214
- const promiseOrVoid = (0, _useAsyncData.load)(itemPath,
215
- // TODO: Revise! Most probably we don't have fully correct loader
216
- // typing, as it may return either promise or value, and those two
217
- // cases call for different runtime behavior, which in turns only
218
- // happens if the outer function on the next line matches the same
219
- // async / sync signature.
220
- // eslint-disable-next-line @typescript-eslint/promise-function-async
221
- (oldData, meta) => localLoader(id, oldData, meta), rc.globalState);
222
- if (promiseOrVoid instanceof Promise) await promiseOrVoid;
223
- }
224
- };
225
-
226
- // TODO: Revise! Most probably we don't have fully correct loader
227
- // typing, as it may return either promise or value, and those two
228
- // cases call for different runtime behavior, which in turns only
229
- // happens if the outer function on the next line matches the same
230
- // async / sync signature.
231
- // eslint-disable-next-line @typescript-eslint/promise-function-async
232
- const reloadSingle = customLoader => reload(
233
- // TODO: Revise! Most probably we don't have fully correct loader
234
- // typing, as it may return either promise or value, and those two
235
- // cases call for different runtime behavior, which in turns only
236
- // happens if the outer function on the next line matches the same
237
- // async / sync signature.
238
- // eslint-disable-next-line @typescript-eslint/promise-function-async
239
- customLoader && ((id, ...args) => customLoader(...args)));
240
- const setSingle = data => {
241
- void reload(() => data);
242
- };
243
- return {
244
- reload,
245
- reloadSingle,
246
- setSingle
247
- };
248
- });
249
- if (!Array.isArray(idOrIds)) {
250
- // TODO: Revise related typings!
251
- const e = localState[idOrIds];
252
- const timestamp = e?.timestamp ?? 0;
253
- return {
254
- data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
255
- loading: !!e?.operationId,
256
- reload: stable.reloadSingle,
257
- set: stable.setSingle,
258
- timestamp
259
- };
260
- }
261
- const res = {
262
- items: {},
263
- loading: false,
264
- reload: stable.reload,
265
- timestamp: Number.MAX_VALUE
266
- };
267
- for (const id of ids) {
268
- // TODO: Revise related typing. Should `localState` have a more specific type?
269
- const e = localState[id];
270
- const loading = !!e?.operationId;
271
- const timestamp = e?.timestamp ?? 0;
272
- res.items[id] = {
273
- data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
274
- loading,
275
- timestamp
276
- };
277
- res.loading ||= loading;
278
- if (res.timestamp > timestamp) res.timestamp = timestamp;
279
- }
280
- return res;
281
- }
282
- var _default = exports.default = useAsyncCollection; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
283
- //# sourceMappingURL=useAsyncCollection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","globalState","getGlobalState","ssrContext","disabled","noSSR","operationId","uuid","itemPath","state","initialValue","promiseOrVoid","load","args","data","Promise","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","ref","useRef","current","stable","useState","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | null> => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n\n // Client-side logic.\n } else {\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await load(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = load(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAGA,IAAAE,oBAAA,GAAAF,OAAA;AAEA,IAAAG,aAAA,GAAAH,OAAA;AAYA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAxBA;AACA;AACA;;AA8EA;AACA;AACA;AACA;AACA;AACA;AACA,SAASO,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,MAAMI,EAAE,IAAIL,GAAG,EAAE;IACpB,IAAIM,QAAQ,GAAGH,UAAU,CAACE,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAAQ;MAAEC,OAAO,EAAE,CAAC,GAAGD,QAAQ,CAACC;IAAQ,CAAC,CAAC,KACnED,QAAQ,GAAG,IAAAE,kCAAoB,EAAU,IAAI,EAAE;MAAED,OAAO,EAAE;IAAE,CAAC,CAAC;IACnEJ,UAAU,CAACE,EAAE,CAAC,GAAGC,QAAQ;EAC3B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AEnCb,GAAG,CAACgF,KAAK,CAACtF,EAAE,CAAC,GAAG;MACduD,IAAI,EAAEjB,MAAM,GAAGvB,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAGiE,CAAC,EAAE7B,IAAI,IAAI,IAAI;MAC9D8B,OAAO;MACPlE;IACF,CAAC;IACDb,GAAG,CAAC+E,OAAO,KAAKA,OAAO;IACvB,IAAI/E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAAmF,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcxD,kBAAkB,EAEjC","ignoreList":[]}
@@ -1,273 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.DEFAULT_MAXAGE = void 0;
8
- exports.load = load;
9
- exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
10
- exports.useAsyncData = useAsyncData;
11
- var _react = require("react");
12
- var _uuid = require("uuid");
13
- var _jsUtils = require("@dr.pogodin/js-utils");
14
- var _GlobalStateProvider = require("./GlobalStateProvider");
15
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
16
- var _utils = require("./utils");
17
- /**
18
- * Loads and uses async data into the GlobalState path.
19
- */
20
-
21
- const DEFAULT_MAXAGE = exports.DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
22
-
23
- // NOTE: Here, and below it is important whether a loader and related
24
- // (re-)loading handlers return a promise or a value, as returning promises
25
- // mean the async mode, in which related global state values are updated
26
- // asynchronously (the new value comes into effect in a next rendering cycle),
27
- // while returning a non-promise value means a synchronous mode, in which
28
- // related global state values are updated immediately, within the current
29
- // rendering cycle.
30
-
31
- function newAsyncDataEnvelope(initialData = null, {
32
- numRefs = 0,
33
- timestamp = 0
34
- } = {}) {
35
- return {
36
- data: initialData,
37
- numRefs,
38
- operationId: '',
39
- timestamp
40
- };
41
- }
42
- /**
43
- * Writes data into the global state, and prints console messages in the debug
44
- * mode.
45
- */
46
- function setState(data, path, gs, prevState = gs.get(path)) {
47
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
- /* eslint-disable no-console */
49
- console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
50
- console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
51
- /* eslint-enable no-console */
52
- }
53
- gs.set(path, {
54
- ...prevState,
55
- data,
56
- operationId: '',
57
- timestamp: Date.now()
58
- });
59
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
60
- /* eslint-disable no-console */
61
- console.groupEnd();
62
- /* eslint-enable no-console */
63
- }
64
- }
65
- function finalizeLoad(data, path, gs, operationId) {
66
- // NOTE: We don't really mean that it hasn't been aborted,
67
- // the "false" flag rather says we don't need to trigger "on aborted"
68
- // callback for this operation, if any is registered - just drop it.
69
- //
70
- // Also, in the synchronous state update mode, we don't really need to set up
71
- // the abort callback at all (as there is no way to use it), but for now it is
72
- // set up, thus it should be cleaned out here.
73
- gs.asyncDataLoadDone(operationId, false);
74
- const state = gs.get(path);
75
- if (operationId === state?.operationId) setState(data, path, gs, state);
76
- }
77
-
78
- /**
79
- * Executes the data loading operation.
80
- * @param path Data segment path inside the global state.
81
- * @param loader Data loader.
82
- * @param globalState The global state instance.
83
- * @param oldData Optional. Previously fetched data, currently stored in
84
- * the state, if already fetched by the caller; otherwise, they will be fetched
85
- * by the load() function itself.
86
- * @param opIdPrefix operationId prefix to use, which should be
87
- * 'C' at the client-side (default), or 'S' at the server-side (within SSR
88
- * context).
89
- * @return Resolves once the operation is done.
90
- * @ignore
91
- */
92
- function load(path, loader, globalState, old,
93
- // TODO: Should this parameter be just a binary flag (client or server),
94
- // and UUID always generated inside this function? Or do we need it in
95
- // the caller methods as well, in some cases (see useAsyncCollection()
96
- // use case as well).
97
- operationId = `C${(0, _uuid.v4)()}`) {
98
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
99
- /* eslint-disable no-console */
100
- console.log(`ReactGlobalState: async data (re-)loading. Path: "${path ?? ''}"`);
101
- /* eslint-enable no-console */
102
- }
103
- const operationIdPath = path ? `${path}.operationId` : 'operationId';
104
- {
105
- const prevOperationId = globalState.get(operationIdPath);
106
- if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);
107
- }
108
- globalState.set(operationIdPath, operationId);
109
- let definedOld = old;
110
- if (!definedOld) {
111
- // TODO: Can we improve the typing, to avoid ForceT?
112
- const e = globalState.get(path);
113
- definedOld = {
114
- data: e.data,
115
- timestamp: e.timestamp
116
- };
117
- }
118
- const dataOrPromise = loader(definedOld.data, {
119
- isAborted: () => {
120
- // TODO: Can we improve the typing, to avoid ForceT?
121
- const opid = globalState.get(path).operationId;
122
- return opid !== operationId;
123
- },
124
- oldDataTimestamp: definedOld.timestamp,
125
- setAbortCallback(cb) {
126
- const opid = globalState.get(path).operationId;
127
- if (opid !== operationId) {
128
- throw Error(`Operation #${operationId} has completed already`);
129
- }
130
- globalState.setAsyncDataAbortCallback(operationId, cb);
131
- }
132
- });
133
- if (dataOrPromise instanceof Promise) {
134
- return dataOrPromise.then(data => {
135
- finalizeLoad(data, path, globalState, operationId);
136
- }).finally(() => {
137
- // NOTE: We don't really mean that it hasn't been aborted,
138
- // the "false" flag rather says we don't need to trigger "on aborted"
139
- // callback for this operation, if any is registered - just drop it.
140
- globalState.asyncDataLoadDone(operationId, false);
141
- });
142
- }
143
- finalizeLoad(dataOrPromise, path, globalState, operationId);
144
- return undefined;
145
- }
146
-
147
- /**
148
- * Resolves asynchronous data, and stores them at given `path` of global
149
- * state.
150
- */
151
-
152
- // TODO: Perhaps split the heap management to a dedicated hook,
153
- // as it is done inside useAsyncCollection().
154
-
155
- function useAsyncData(path, loader, options = {}) {
156
- const maxage = options.maxage ?? DEFAULT_MAXAGE;
157
- const refreshAge = options.refreshAge ?? maxage;
158
- const garbageCollectAge = options.garbageCollectAge ?? maxage;
159
-
160
- // Note: here we can't depend on useGlobalState() to init the initial value,
161
- // because that way we'll have issues with SSR (see details below).
162
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
163
- const state = globalState.get(path, {
164
- initialValue: newAsyncDataEnvelope()
165
- });
166
- const {
167
- current: heap
168
- } = (0, _react.useRef)({});
169
- heap.globalState = globalState;
170
- heap.path = path;
171
- heap.loader = loader;
172
- heap.reload ??= customLoader => {
173
- const localLoader = customLoader ?? heap.loader;
174
- if (!localLoader || !heap.globalState) throw Error('Internal error');
175
- return load(heap.path, localLoader, heap.globalState);
176
- };
177
- heap.set ??= data => {
178
- if (!heap.globalState) throw Error('Internal error');
179
- setState(data, heap.path, heap.globalState);
180
- };
181
- if (globalState.ssrContext) {
182
- if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
183
- const promiseOrVoid = load(path, loader, globalState, {
184
- data: state.data,
185
- timestamp: state.timestamp
186
- }, `S${(0, _uuid.v4)()}`);
187
- if (promiseOrVoid instanceof Promise) {
188
- globalState.ssrContext.pending.push(promiseOrVoid);
189
- }
190
- }
191
- } else {
192
- const {
193
- disabled
194
- } = options;
195
-
196
- // This takes care about the client-side reference counting, and garbage
197
- // collection.
198
- //
199
- // Note: the Rules of Hook below are violated by conditional call to a hook,
200
- // but as the condition is actually server-side or client-side environment,
201
- // it is effectively non-conditional at the runtime.
202
- //
203
- // TODO: Though, maybe there is a way to refactor it into a cleaner code.
204
- // The same applies to other useEffect() hooks below.
205
- (0, _react.useEffect)(() => {
206
- // eslint-disable-line react-hooks/rules-of-hooks
207
- const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
208
- if (!disabled) {
209
- const numRefs = globalState.get(numRefsPath);
210
- globalState.set(numRefsPath, numRefs + 1);
211
- }
212
- return () => {
213
- if (!disabled) {
214
- const state2 = globalState.get(path);
215
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
216
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
217
- /* eslint-disable no-console */
218
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path ?? ''}`);
219
- /* eslint-enable no-console */
220
- }
221
- globalState.dropDependencies(path ?? '');
222
- globalState.set(path, {
223
- ...state2,
224
- data: null,
225
- numRefs: 0,
226
- timestamp: 0
227
- });
228
- } else {
229
- globalState.set(numRefsPath, state2.numRefs - 1);
230
- }
231
- }
232
- };
233
- }, [disabled, garbageCollectAge, globalState, path]);
234
-
235
- // Note: a bunch of Rules of Hooks ignored belows because in our very
236
- // special case the otherwise wrong behavior is actually what we need.
237
-
238
- // Data loading and refreshing.
239
- (0, _react.useEffect)(() => {
240
- // eslint-disable-line react-hooks/rules-of-hooks
241
- if (!disabled) {
242
- const state2 = globalState.get(path);
243
- const {
244
- deps
245
- } = options;
246
- if (
247
- // The hook is called with a list of dependencies, that mismatch
248
- // dependencies last used to retrieve the data at given path.
249
- deps && globalState.hasChangedDependencies(path ?? '', deps)
250
-
251
- // Data at the path are stale, and are not being loaded.
252
- || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.startsWith('S'))) {
253
- if (!deps) globalState.dropDependencies(path ?? '');
254
- void load(path, loader, globalState, {
255
- data: state2.data,
256
- timestamp: state2.timestamp
257
- });
258
- }
259
- }
260
- });
261
- }
262
- const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
263
- return {
264
- data: maxage < Date.now() - localState.timestamp ? null : localState.data,
265
- loading: Boolean(localState.operationId),
266
- reload: heap.reload,
267
- set: heap.set,
268
- timestamp: localState.timestamp
269
- };
270
- }
271
-
272
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
273
- //# sourceMappingURL=useAsyncData.js.map