@dr.pogodin/react-global-state 0.19.1 → 0.19.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.
- package/build/cjs/GlobalState.js +289 -0
- package/build/cjs/GlobalState.js.map +1 -0
- package/build/cjs/GlobalStateProvider.js +97 -0
- package/build/cjs/GlobalStateProvider.js.map +1 -0
- package/build/cjs/SsrContext.js +15 -0
- package/build/cjs/SsrContext.js.map +1 -0
- package/build/cjs/index.js +88 -0
- package/build/cjs/index.js.map +1 -0
- package/build/cjs/useAsyncCollection.js +270 -0
- package/build/cjs/useAsyncCollection.js.map +1 -0
- package/build/cjs/useAsyncData.js +260 -0
- package/build/cjs/useAsyncData.js.map +1 -0
- package/build/cjs/useGlobalState.js +149 -0
- package/build/cjs/useGlobalState.js.map +1 -0
- package/build/cjs/utils.js +91 -0
- package/build/cjs/utils.js.map +1 -0
- package/package.json +4 -2
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
const res = [...idOrIds];
|
|
83
|
+
res.sort((a, b) => a.toString().localeCompare(b.toString()));
|
|
84
|
+
return res;
|
|
85
|
+
}
|
|
86
|
+
return [idOrIds];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Inits/updates, and returns the heap.
|
|
91
|
+
*/
|
|
92
|
+
function useHeap(ids, path, loader, gs) {
|
|
93
|
+
const ref = (0, _react.useRef)(undefined);
|
|
94
|
+
let heap = ref.current;
|
|
95
|
+
if (heap) {
|
|
96
|
+
// Update.
|
|
97
|
+
heap.ids = ids;
|
|
98
|
+
heap.path = path;
|
|
99
|
+
heap.loader = loader;
|
|
100
|
+
heap.globalState = gs;
|
|
101
|
+
} else {
|
|
102
|
+
// Initialization.
|
|
103
|
+
const reload = async customLoader => {
|
|
104
|
+
const heap2 = ref.current;
|
|
105
|
+
const localLoader = customLoader ?? heap2.loader;
|
|
106
|
+
// TODO: Revise - not sure all related typing is 100% correct,
|
|
107
|
+
// thus let's keep this runtime assertion.
|
|
108
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
109
|
+
if (!localLoader || !heap2.globalState || !heap2.ids) {
|
|
110
|
+
throw Error('Internal error');
|
|
111
|
+
}
|
|
112
|
+
for (const id of heap2.ids) {
|
|
113
|
+
const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
|
|
114
|
+
const promiseOrVoid = (0, _useAsyncData.load)(itemPath,
|
|
115
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
116
|
+
// typing, as it may return either promise or value, and those two
|
|
117
|
+
// cases call for different runtime behavior, which in turns only
|
|
118
|
+
// happens if the outer function on the next line matches the same
|
|
119
|
+
// async / sync signature.
|
|
120
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
121
|
+
(oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
|
|
122
|
+
if (promiseOrVoid instanceof Promise) await promiseOrVoid;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
heap = {
|
|
126
|
+
globalState: gs,
|
|
127
|
+
ids,
|
|
128
|
+
loader,
|
|
129
|
+
path,
|
|
130
|
+
reload,
|
|
131
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
132
|
+
// typing, as it may return either promise or value, and those two
|
|
133
|
+
// cases call for different runtime behavior, which in turns only
|
|
134
|
+
// happens if the outer function on the next line matches the same
|
|
135
|
+
// async / sync signature.
|
|
136
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
137
|
+
reloadSingle: customLoader => ref.current.reload(
|
|
138
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
139
|
+
// typing, as it may return either promise or value, and those two
|
|
140
|
+
// cases call for different runtime behavior, which in turns only
|
|
141
|
+
// happens if the outer function on the next line matches the same
|
|
142
|
+
// async / sync signature.
|
|
143
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
144
|
+
customLoader && ((id, ...args) => customLoader(...args)))
|
|
145
|
+
};
|
|
146
|
+
ref.current = heap;
|
|
147
|
+
}
|
|
148
|
+
return heap;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Resolves and stores at the given `path` of the global state elements of
|
|
153
|
+
* an asynchronous data collection.
|
|
154
|
+
*/
|
|
155
|
+
|
|
156
|
+
// TODO: This is largely similar to useAsyncData() logic, just more generic.
|
|
157
|
+
// Perhaps, a bunch of logic blocks can be split into stand-alone functions,
|
|
158
|
+
// and reused in both hooks.
|
|
159
|
+
// eslint-disable-next-line complexity
|
|
160
|
+
function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
161
|
+
const ids = normalizeIds(idOrIds);
|
|
162
|
+
const maxage = options.maxage ?? _useAsyncData.DEFAULT_MAXAGE;
|
|
163
|
+
const refreshAge = options.refreshAge ?? maxage;
|
|
164
|
+
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
165
|
+
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
166
|
+
const heap = useHeap(ids, path, loader, globalState);
|
|
167
|
+
|
|
168
|
+
// Server-side logic.
|
|
169
|
+
if (globalState.ssrContext && !options.noSSR) {
|
|
170
|
+
const operationId = `S${(0, _uuid.v4)()}`;
|
|
171
|
+
for (const id of ids) {
|
|
172
|
+
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
173
|
+
const state = globalState.get(itemPath, {
|
|
174
|
+
initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
|
|
175
|
+
});
|
|
176
|
+
if (!state.timestamp && !state.operationId) {
|
|
177
|
+
const promiseOrVoid = (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
|
|
178
|
+
data: state.data,
|
|
179
|
+
timestamp: state.timestamp
|
|
180
|
+
}, operationId);
|
|
181
|
+
if (promiseOrVoid instanceof Promise) {
|
|
182
|
+
globalState.ssrContext.pending.push(promiseOrVoid);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Client-side logic.
|
|
188
|
+
} else {
|
|
189
|
+
// Reference-counting & garbage collection.
|
|
190
|
+
|
|
191
|
+
const idsHash = (0, _utils.hash)(ids);
|
|
192
|
+
|
|
193
|
+
// TODO: Violation of rules of hooks is fine here,
|
|
194
|
+
// but perhaps it can be refactored to avoid the need for it.
|
|
195
|
+
(0, _react.useEffect)(() => {
|
|
196
|
+
// eslint-disable-line react-hooks/rules-of-hooks
|
|
197
|
+
gcOnWithhold(ids, path, globalState);
|
|
198
|
+
return () => {
|
|
199
|
+
gcOnRelease(ids, path, globalState, garbageCollectAge);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// `ids` are represented in the dependencies array by `idsHash` value,
|
|
203
|
+
// as useEffect() hook requires a constant size of dependencies array.
|
|
204
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
205
|
+
}, [garbageCollectAge, globalState, idsHash, path]);
|
|
206
|
+
|
|
207
|
+
// NOTE: a bunch of Rules of Hooks ignored belows because in our very
|
|
208
|
+
// special case the otherwise wrong behavior is actually what we need.
|
|
209
|
+
|
|
210
|
+
// Data loading and refreshing.
|
|
211
|
+
(0, _react.useEffect)(() => {
|
|
212
|
+
// eslint-disable-line react-hooks/rules-of-hooks
|
|
213
|
+
void (async () => {
|
|
214
|
+
for (const id of ids) {
|
|
215
|
+
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
216
|
+
const state2 = globalState.get(itemPath);
|
|
217
|
+
const {
|
|
218
|
+
deps
|
|
219
|
+
} = options;
|
|
220
|
+
if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
|
|
221
|
+
if (!deps) globalState.dropDependencies(itemPath);
|
|
222
|
+
await (0, _useAsyncData.load)(itemPath,
|
|
223
|
+
// TODO: I guess, the loader is not correctly typed here -
|
|
224
|
+
// it can be synchronous, and in that case the following method
|
|
225
|
+
// should be kept synchronous to not alter the sync logic.
|
|
226
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
227
|
+
(old, ...args) => loader(id, old, ...args), globalState, {
|
|
228
|
+
data: state2?.data,
|
|
229
|
+
timestamp: state2?.timestamp ?? 0
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
})();
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
const [localState] = (0, _useGlobalState.default)(path, {});
|
|
237
|
+
if (!Array.isArray(idOrIds)) {
|
|
238
|
+
// TODO: Revise related typings!
|
|
239
|
+
const e = localState[idOrIds];
|
|
240
|
+
const timestamp = e?.timestamp ?? 0;
|
|
241
|
+
return {
|
|
242
|
+
data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
|
|
243
|
+
loading: !!e?.operationId,
|
|
244
|
+
reload: heap.reloadSingle,
|
|
245
|
+
timestamp
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
const res = {
|
|
249
|
+
items: {},
|
|
250
|
+
loading: false,
|
|
251
|
+
reload: heap.reload,
|
|
252
|
+
timestamp: Number.MAX_VALUE
|
|
253
|
+
};
|
|
254
|
+
for (const id of ids) {
|
|
255
|
+
// TODO: Revise related typing. Should `localState` have a more specific type?
|
|
256
|
+
const e = localState[id];
|
|
257
|
+
const loading = !!e?.operationId;
|
|
258
|
+
const timestamp = e?.timestamp ?? 0;
|
|
259
|
+
res.items[id] = {
|
|
260
|
+
data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
|
|
261
|
+
loading,
|
|
262
|
+
timestamp
|
|
263
|
+
};
|
|
264
|
+
res.loading ||= loading;
|
|
265
|
+
if (res.timestamp > timestamp) res.timestamp = timestamp;
|
|
266
|
+
}
|
|
267
|
+
return res;
|
|
268
|
+
}
|
|
269
|
+
var _default = exports.default = useAsyncCollection; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
270
|
+
//# sourceMappingURL=useAsyncCollection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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","sort","a","b","localeCompare","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","load","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","data","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","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 } 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> =\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>\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 HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\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 const res = [...idOrIds];\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>(undefined);\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader ?? heap2.loader;\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 || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (const id of heap2.ids) {\n const itemPath = heap2.path ? `${heap2.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 heap2.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n heap = {\n globalState: gs,\n ids,\n loader,\n path,\n 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 reloadSingle: (customLoader) => ref.current!.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 ref.current = heap;\n }\n\n return heap;\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 const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !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 // Client-side logic.\n } else {\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 gcOnWithhold(ids, path, globalState);\n return () => {\n 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 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 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 const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\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: heap.reloadSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.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;;AAgFA;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,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AS,GAAG,IAAI,GAAG+D,CAAC,EAAEd,IAAI,IAAI,IAAI;MAC9De,OAAO;MACPhE;IACF,CAAC;IACDb,GAAG,CAAC6E,OAAO,KAAKA,OAAO;IACvB,IAAI7E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAAiF,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB,EAEjC","ignoreList":[]}
|
|
@@ -0,0 +1,260 @@
|
|
|
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
|
+
function finalizeLoad(data, path, globalState, operationId) {
|
|
43
|
+
// NOTE: We don't really mean that it hasn't been aborted,
|
|
44
|
+
// the "false" flag rather says we don't need to trigger "on aborted"
|
|
45
|
+
// callback for this operation, if any is registered - just drop it.
|
|
46
|
+
//
|
|
47
|
+
// Also, in the synchronous state update mode, we don't really need to set up
|
|
48
|
+
// the abort callback at all (as there is no way to use it), but for now it is
|
|
49
|
+
// set up, thus it should be cleaned out here.
|
|
50
|
+
globalState.asyncDataLoadDone(operationId, false);
|
|
51
|
+
const state = globalState.get(path);
|
|
52
|
+
if (operationId === state?.operationId) {
|
|
53
|
+
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
54
|
+
/* eslint-disable no-console */
|
|
55
|
+
console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
|
|
56
|
+
console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
|
|
57
|
+
/* eslint-enable no-console */
|
|
58
|
+
}
|
|
59
|
+
globalState.set(path, {
|
|
60
|
+
...state,
|
|
61
|
+
data,
|
|
62
|
+
operationId: '',
|
|
63
|
+
timestamp: Date.now()
|
|
64
|
+
});
|
|
65
|
+
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
66
|
+
/* eslint-disable no-console */
|
|
67
|
+
console.groupEnd();
|
|
68
|
+
/* eslint-enable no-console */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Executes the data loading operation.
|
|
75
|
+
* @param path Data segment path inside the global state.
|
|
76
|
+
* @param loader Data loader.
|
|
77
|
+
* @param globalState The global state instance.
|
|
78
|
+
* @param oldData Optional. Previously fetched data, currently stored in
|
|
79
|
+
* the state, if already fetched by the caller; otherwise, they will be fetched
|
|
80
|
+
* by the load() function itself.
|
|
81
|
+
* @param opIdPrefix operationId prefix to use, which should be
|
|
82
|
+
* 'C' at the client-side (default), or 'S' at the server-side (within SSR
|
|
83
|
+
* context).
|
|
84
|
+
* @return Resolves once the operation is done.
|
|
85
|
+
* @ignore
|
|
86
|
+
*/
|
|
87
|
+
function load(path, loader, globalState, old,
|
|
88
|
+
// TODO: Should this parameter be just a binary flag (client or server),
|
|
89
|
+
// and UUID always generated inside this function? Or do we need it in
|
|
90
|
+
// the caller methods as well, in some cases (see useAsyncCollection()
|
|
91
|
+
// use case as well).
|
|
92
|
+
operationId = `C${(0, _uuid.v4)()}`) {
|
|
93
|
+
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
94
|
+
/* eslint-disable no-console */
|
|
95
|
+
console.log(`ReactGlobalState: async data (re-)loading. Path: "${path ?? ''}"`);
|
|
96
|
+
/* eslint-enable no-console */
|
|
97
|
+
}
|
|
98
|
+
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
99
|
+
{
|
|
100
|
+
const prevOperationId = globalState.get(operationIdPath);
|
|
101
|
+
if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);
|
|
102
|
+
}
|
|
103
|
+
globalState.set(operationIdPath, operationId);
|
|
104
|
+
let definedOld = old;
|
|
105
|
+
if (!definedOld) {
|
|
106
|
+
// TODO: Can we improve the typing, to avoid ForceT?
|
|
107
|
+
const e = globalState.get(path);
|
|
108
|
+
definedOld = {
|
|
109
|
+
data: e.data,
|
|
110
|
+
timestamp: e.timestamp
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const dataOrPromise = loader(definedOld.data, {
|
|
114
|
+
isAborted: () => {
|
|
115
|
+
// TODO: Can we improve the typing, to avoid ForceT?
|
|
116
|
+
const opid = globalState.get(path).operationId;
|
|
117
|
+
return opid !== operationId;
|
|
118
|
+
},
|
|
119
|
+
oldDataTimestamp: definedOld.timestamp,
|
|
120
|
+
setAbortCallback(cb) {
|
|
121
|
+
const opid = globalState.get(path).operationId;
|
|
122
|
+
if (opid !== operationId) {
|
|
123
|
+
throw Error(`Operation #${operationId} has completed already`);
|
|
124
|
+
}
|
|
125
|
+
globalState.setAsyncDataAbortCallback(operationId, cb);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
if (dataOrPromise instanceof Promise) {
|
|
129
|
+
return dataOrPromise.then(data => {
|
|
130
|
+
finalizeLoad(data, path, globalState, operationId);
|
|
131
|
+
}).finally(() => {
|
|
132
|
+
// NOTE: We don't really mean that it hasn't been aborted,
|
|
133
|
+
// the "false" flag rather says we don't need to trigger "on aborted"
|
|
134
|
+
// callback for this operation, if any is registered - just drop it.
|
|
135
|
+
globalState.asyncDataLoadDone(operationId, false);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
finalizeLoad(dataOrPromise, path, globalState, operationId);
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Resolves asynchronous data, and stores them at given `path` of global
|
|
144
|
+
* state.
|
|
145
|
+
*/
|
|
146
|
+
|
|
147
|
+
function useAsyncData(path, loader, options = {}) {
|
|
148
|
+
const maxage = options.maxage ?? DEFAULT_MAXAGE;
|
|
149
|
+
const refreshAge = options.refreshAge ?? maxage;
|
|
150
|
+
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
151
|
+
|
|
152
|
+
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
153
|
+
// because that way we'll have issues with SSR (see details below).
|
|
154
|
+
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
155
|
+
const state = globalState.get(path, {
|
|
156
|
+
initialValue: newAsyncDataEnvelope()
|
|
157
|
+
});
|
|
158
|
+
const {
|
|
159
|
+
current: heap
|
|
160
|
+
} = (0, _react.useRef)({});
|
|
161
|
+
heap.globalState = globalState;
|
|
162
|
+
heap.path = path;
|
|
163
|
+
heap.loader = loader;
|
|
164
|
+
heap.reload ??= customLoader => {
|
|
165
|
+
const localLoader = customLoader ?? heap.loader;
|
|
166
|
+
if (!localLoader || !heap.globalState) throw Error('Internal error');
|
|
167
|
+
return load(heap.path, localLoader, heap.globalState);
|
|
168
|
+
};
|
|
169
|
+
if (globalState.ssrContext) {
|
|
170
|
+
if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
|
|
171
|
+
const promiseOrVoid = load(path, loader, globalState, {
|
|
172
|
+
data: state.data,
|
|
173
|
+
timestamp: state.timestamp
|
|
174
|
+
}, `S${(0, _uuid.v4)()}`);
|
|
175
|
+
if (promiseOrVoid instanceof Promise) {
|
|
176
|
+
globalState.ssrContext.pending.push(promiseOrVoid);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} else {
|
|
180
|
+
const {
|
|
181
|
+
disabled
|
|
182
|
+
} = options;
|
|
183
|
+
|
|
184
|
+
// This takes care about the client-side reference counting, and garbage
|
|
185
|
+
// collection.
|
|
186
|
+
//
|
|
187
|
+
// Note: the Rules of Hook below are violated by conditional call to a hook,
|
|
188
|
+
// but as the condition is actually server-side or client-side environment,
|
|
189
|
+
// it is effectively non-conditional at the runtime.
|
|
190
|
+
//
|
|
191
|
+
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
192
|
+
// The same applies to other useEffect() hooks below.
|
|
193
|
+
(0, _react.useEffect)(() => {
|
|
194
|
+
// eslint-disable-line react-hooks/rules-of-hooks
|
|
195
|
+
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
196
|
+
if (!disabled) {
|
|
197
|
+
const numRefs = globalState.get(numRefsPath);
|
|
198
|
+
globalState.set(numRefsPath, numRefs + 1);
|
|
199
|
+
}
|
|
200
|
+
return () => {
|
|
201
|
+
if (!disabled) {
|
|
202
|
+
const state2 = globalState.get(path);
|
|
203
|
+
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
204
|
+
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
205
|
+
/* eslint-disable no-console */
|
|
206
|
+
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path ?? ''}`);
|
|
207
|
+
/* eslint-enable no-console */
|
|
208
|
+
}
|
|
209
|
+
globalState.dropDependencies(path ?? '');
|
|
210
|
+
globalState.set(path, {
|
|
211
|
+
...state2,
|
|
212
|
+
data: null,
|
|
213
|
+
numRefs: 0,
|
|
214
|
+
timestamp: 0
|
|
215
|
+
});
|
|
216
|
+
} else {
|
|
217
|
+
globalState.set(numRefsPath, state2.numRefs - 1);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}, [disabled, garbageCollectAge, globalState, path]);
|
|
222
|
+
|
|
223
|
+
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
224
|
+
// special case the otherwise wrong behavior is actually what we need.
|
|
225
|
+
|
|
226
|
+
// Data loading and refreshing.
|
|
227
|
+
(0, _react.useEffect)(() => {
|
|
228
|
+
// eslint-disable-line react-hooks/rules-of-hooks
|
|
229
|
+
if (!disabled) {
|
|
230
|
+
const state2 = globalState.get(path);
|
|
231
|
+
const {
|
|
232
|
+
deps
|
|
233
|
+
} = options;
|
|
234
|
+
if (
|
|
235
|
+
// The hook is called with a list of dependencies, that mismatch
|
|
236
|
+
// dependencies last used to retrieve the data at given path.
|
|
237
|
+
deps && globalState.hasChangedDependencies(path ?? '', deps)
|
|
238
|
+
|
|
239
|
+
// Data at the path are stale, and are not being loaded.
|
|
240
|
+
|| refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.startsWith('S'))) {
|
|
241
|
+
if (!deps) globalState.dropDependencies(path ?? '');
|
|
242
|
+
void load(path, loader, globalState, {
|
|
243
|
+
data: state2.data,
|
|
244
|
+
timestamp: state2.timestamp
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
|
|
251
|
+
return {
|
|
252
|
+
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
253
|
+
loading: Boolean(localState.operationId),
|
|
254
|
+
reload: heap.reload,
|
|
255
|
+
timestamp: localState.timestamp
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
260
|
+
//# sourceMappingURL=useAsyncData.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","load","loader","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => (DataT | null) | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): void | Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\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 const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBO,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAkBA,SA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