@dr.pogodin/react-global-state 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/build/{module → code}/GlobalState.js +15 -5
- package/build/code/GlobalState.js.map +1 -0
- package/build/{module → code}/GlobalStateProvider.js +18 -18
- package/build/code/GlobalStateProvider.js.map +1 -0
- package/build/code/SsrContext.js.map +1 -0
- package/build/{module → code}/index.js +9 -3
- package/build/code/index.js.map +1 -0
- package/build/{module → code}/useAsyncCollection.js +60 -27
- package/build/code/useAsyncCollection.js.map +1 -0
- package/build/{module → code}/useAsyncData.js +19 -17
- package/build/code/useAsyncData.js.map +1 -0
- package/build/{module → code}/useGlobalState.js +25 -8
- package/build/code/useGlobalState.js.map +1 -0
- package/build/{module → code}/utils.js +1 -1
- package/build/code/utils.js.map +1 -0
- package/build/types/GlobalState.d.ts +2 -2
- package/build/types/GlobalStateProvider.d.ts +3 -3
- package/build/types/SsrContext.d.ts +3 -3
- package/build/types/useAsyncCollection.d.ts +4 -6
- package/build/types/useAsyncData.d.ts +2 -2
- package/build/types/utils.d.ts +2 -3
- package/eslint.config.mjs +19 -0
- package/package.json +25 -41
- package/build/common/GlobalState.js +0 -279
- package/build/common/GlobalState.js.map +0 -1
- package/build/common/GlobalStateProvider.js +0 -97
- package/build/common/GlobalStateProvider.js.map +0 -1
- package/build/common/SsrContext.js +0 -15
- package/build/common/SsrContext.js.map +0 -1
- package/build/common/index.js +0 -84
- package/build/common/index.js.map +0 -1
- package/build/common/useAsyncCollection.js +0 -242
- package/build/common/useAsyncCollection.js.map +0 -1
- package/build/common/useAsyncData.js +0 -233
- package/build/common/useAsyncData.js.map +0 -1
- package/build/common/useGlobalState.js +0 -134
- package/build/common/useGlobalState.js.map +0 -1
- package/build/common/utils.js +0 -91
- package/build/common/utils.js.map +0 -1
- package/build/module/GlobalState.js.map +0 -1
- package/build/module/GlobalStateProvider.js.map +0 -1
- package/build/module/SsrContext.js.map +0 -1
- package/build/module/index.js.map +0 -1
- package/build/module/useAsyncCollection.js.map +0 -1
- package/build/module/useAsyncData.js.map +0 -1
- package/build/module/useGlobalState.js.map +0 -1
- package/build/module/utils.js.map +0 -1
- package/src/GlobalState.ts +0 -342
- package/src/GlobalStateProvider.tsx +0 -117
- package/src/SsrContext.ts +0 -11
- package/src/index.ts +0 -84
- package/src/useAsyncCollection.ts +0 -471
- package/src/useAsyncData.ts +0 -362
- package/src/useGlobalState.ts +0 -225
- package/src/utils.ts +0 -116
- /package/build/{module → code}/SsrContext.js +0 -0
|
@@ -1,242 +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 (let i = 0; i < ids.length; ++i) {
|
|
29
|
-
const id = ids[i];
|
|
30
|
-
let envelope = collection[id];
|
|
31
|
-
if (envelope) envelope = {
|
|
32
|
-
...envelope,
|
|
33
|
-
numRefs: 1 + envelope.numRefs
|
|
34
|
-
};else envelope = (0, _useAsyncData.newAsyncDataEnvelope)(null, {
|
|
35
|
-
numRefs: 1
|
|
36
|
-
});
|
|
37
|
-
collection[id] = envelope;
|
|
38
|
-
}
|
|
39
|
-
gs.set(path, collection);
|
|
40
|
-
}
|
|
41
|
-
function idsToStringSet(ids) {
|
|
42
|
-
const res = new Set();
|
|
43
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
44
|
-
res.add(ids[i].toString());
|
|
45
|
-
}
|
|
46
|
-
return res;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* GarbageCollector: the piece of logic executed on un-mounting of
|
|
51
|
-
* an useAsyncCollection() hook, and on update of hook params, to clean-up
|
|
52
|
-
* after the previous param values. It decrements by 1 `numRefs` counters
|
|
53
|
-
* for previously requested collection items, and also drops from the state
|
|
54
|
-
* stale records.
|
|
55
|
-
*/
|
|
56
|
-
function gcOnRelease(ids, path, gs, gcAge) {
|
|
57
|
-
const entries = Object.entries(gs.get(path));
|
|
58
|
-
const now = Date.now();
|
|
59
|
-
const idSet = idsToStringSet(ids);
|
|
60
|
-
const collection = {};
|
|
61
|
-
for (let i = 0; i < entries.length; ++i) {
|
|
62
|
-
const [id, envelope] = entries[i];
|
|
63
|
-
if (envelope) {
|
|
64
|
-
const toBeReleased = idSet.has(id);
|
|
65
|
-
let {
|
|
66
|
-
numRefs
|
|
67
|
-
} = envelope;
|
|
68
|
-
if (toBeReleased) --numRefs;
|
|
69
|
-
if (gcAge > now - envelope.timestamp || numRefs > 0) {
|
|
70
|
-
collection[id] = toBeReleased ? {
|
|
71
|
-
...envelope,
|
|
72
|
-
numRefs
|
|
73
|
-
} : envelope;
|
|
74
|
-
} else if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
75
|
-
// eslint-disable-next-line no-console
|
|
76
|
-
console.log(`useAsyncCollection(): Garbage collected at the path "${path}", ID = ${id}`);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
gs.set(path, collection);
|
|
81
|
-
}
|
|
82
|
-
function normalizeIds(idOrIds) {
|
|
83
|
-
if (Array.isArray(idOrIds)) {
|
|
84
|
-
const res = [...idOrIds];
|
|
85
|
-
res.sort();
|
|
86
|
-
return res;
|
|
87
|
-
}
|
|
88
|
-
return [idOrIds];
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Inits/updates, and returns the heap.
|
|
93
|
-
*/
|
|
94
|
-
function useHeap(ids, path, loader, gs) {
|
|
95
|
-
const ref = (0, _react.useRef)(undefined);
|
|
96
|
-
let heap = ref.current;
|
|
97
|
-
if (heap) {
|
|
98
|
-
// Update.
|
|
99
|
-
heap.ids = ids;
|
|
100
|
-
heap.path = path;
|
|
101
|
-
heap.loader = loader;
|
|
102
|
-
heap.globalState = gs;
|
|
103
|
-
} else {
|
|
104
|
-
// Initialization.
|
|
105
|
-
const reload = async customLoader => {
|
|
106
|
-
const heap2 = ref.current;
|
|
107
|
-
const localLoader = customLoader || heap2.loader;
|
|
108
|
-
if (!localLoader || !heap2.globalState || !heap2.ids) {
|
|
109
|
-
throw Error('Internal error');
|
|
110
|
-
}
|
|
111
|
-
for (let i = 0; i < heap2.ids.length; ++i) {
|
|
112
|
-
const id = heap2.ids[i];
|
|
113
|
-
const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
|
|
114
|
-
|
|
115
|
-
// eslint-disable-next-line no-await-in-loop
|
|
116
|
-
await (0, _useAsyncData.load)(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
heap = {
|
|
120
|
-
globalState: gs,
|
|
121
|
-
ids,
|
|
122
|
-
path,
|
|
123
|
-
loader,
|
|
124
|
-
reload,
|
|
125
|
-
reloadSingle: customLoader => ref.current.reload(customLoader && ((id, ...args) => customLoader(...args)))
|
|
126
|
-
};
|
|
127
|
-
ref.current = heap;
|
|
128
|
-
}
|
|
129
|
-
return heap;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Resolves and stores at the given `path` of the global state elements of
|
|
134
|
-
* an asynchronous data collection.
|
|
135
|
-
*/
|
|
136
|
-
|
|
137
|
-
// TODO: This is largely similar to useAsyncData() logic, just more generic.
|
|
138
|
-
// Perhaps, a bunch of logic blocks can be split into stand-alone functions,
|
|
139
|
-
// and reused in both hooks.
|
|
140
|
-
function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
141
|
-
const ids = normalizeIds(idOrIds);
|
|
142
|
-
const maxage = options.maxage ?? _useAsyncData.DEFAULT_MAXAGE;
|
|
143
|
-
const refreshAge = options.refreshAge ?? maxage;
|
|
144
|
-
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
145
|
-
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
146
|
-
const heap = useHeap(ids, path, loader, globalState);
|
|
147
|
-
|
|
148
|
-
// Server-side logic.
|
|
149
|
-
if (globalState.ssrContext && !options.noSSR) {
|
|
150
|
-
const operationId = `S${(0, _uuid.v4)()}`;
|
|
151
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
152
|
-
const id = ids[i];
|
|
153
|
-
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
154
|
-
const state = globalState.get(itemPath, {
|
|
155
|
-
initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
|
|
156
|
-
});
|
|
157
|
-
if (!state.timestamp && !state.operationId) {
|
|
158
|
-
globalState.ssrContext.pending.push((0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
|
|
159
|
-
data: state.data,
|
|
160
|
-
timestamp: state.timestamp
|
|
161
|
-
}, operationId));
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Client-side logic.
|
|
166
|
-
} else {
|
|
167
|
-
// Reference-counting & garbage collection.
|
|
168
|
-
|
|
169
|
-
const idsHash = (0, _utils.hash)(ids);
|
|
170
|
-
|
|
171
|
-
// TODO: Violation of rules of hooks is fine here,
|
|
172
|
-
// but perhaps it can be refactored to avoid the need for it.
|
|
173
|
-
(0, _react.useEffect)(() => {
|
|
174
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
175
|
-
gcOnWithhold(ids, path, globalState);
|
|
176
|
-
return () => gcOnRelease(ids, path, globalState, garbageCollectAge);
|
|
177
|
-
|
|
178
|
-
// `ids` are represented in the dependencies array by `idsHash` value,
|
|
179
|
-
// as useEffect() hook requires a constant size of dependencies array.
|
|
180
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
181
|
-
}, [garbageCollectAge, globalState, idsHash, path]);
|
|
182
|
-
|
|
183
|
-
// NOTE: a bunch of Rules of Hooks ignored belows because in our very
|
|
184
|
-
// special case the otherwise wrong behavior is actually what we need.
|
|
185
|
-
|
|
186
|
-
// Data loading and refreshing.
|
|
187
|
-
(0, _react.useEffect)(() => {
|
|
188
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
189
|
-
(async () => {
|
|
190
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
191
|
-
const id = ids[i];
|
|
192
|
-
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
193
|
-
const state2 = globalState.get(itemPath);
|
|
194
|
-
const {
|
|
195
|
-
deps
|
|
196
|
-
} = options;
|
|
197
|
-
if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.charAt(0) === 'S')) {
|
|
198
|
-
if (!deps) globalState.dropDependencies(itemPath);
|
|
199
|
-
// eslint-disable-next-line no-await-in-loop
|
|
200
|
-
await (0, _useAsyncData.load)(itemPath, (old, ...args) => loader(id, old, ...args), globalState, {
|
|
201
|
-
data: state2?.data,
|
|
202
|
-
timestamp: state2?.timestamp ?? 0
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
})();
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
const [localState] = (0, _useGlobalState.default)(path, {});
|
|
210
|
-
if (!Array.isArray(idOrIds)) {
|
|
211
|
-
const e = localState[idOrIds];
|
|
212
|
-
const timestamp = e?.timestamp ?? 0;
|
|
213
|
-
return {
|
|
214
|
-
data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
|
|
215
|
-
loading: !!e?.operationId,
|
|
216
|
-
reload: heap.reloadSingle,
|
|
217
|
-
timestamp
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
const res = {
|
|
221
|
-
items: {},
|
|
222
|
-
loading: false,
|
|
223
|
-
reload: heap.reload,
|
|
224
|
-
timestamp: Number.MAX_VALUE
|
|
225
|
-
};
|
|
226
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
227
|
-
const id = ids[i];
|
|
228
|
-
const e = localState[id];
|
|
229
|
-
const loading = !!e?.operationId;
|
|
230
|
-
const timestamp = e?.timestamp ?? 0;
|
|
231
|
-
res.items[id] = {
|
|
232
|
-
data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
|
|
233
|
-
loading,
|
|
234
|
-
timestamp
|
|
235
|
-
};
|
|
236
|
-
res.loading ||= loading;
|
|
237
|
-
if (res.timestamp > timestamp) res.timestamp = timestamp;
|
|
238
|
-
}
|
|
239
|
-
return res;
|
|
240
|
-
}
|
|
241
|
-
var _default = exports.default = useAsyncCollection;
|
|
242
|
-
//# 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","i","length","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","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","load","oldData","meta","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","pending","push","data","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","charAt","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 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> = { [id in 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 | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => 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: {\n [id in IdT]: CollectionItemT<DataT>;\n }\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\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 (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.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 (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\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();\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 if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\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}`> =\n 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}`> =\n 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\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.\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\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 () => gcOnRelease(ids, path, globalState, garbageCollectAge);\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 (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\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.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\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, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\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\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"],"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;;AAkFA;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,IAAII,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,IAAIG,QAAQ,GAAGL,UAAU,CAACI,EAA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,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,MAAM+E,CAAC,GAAGF,UAAU,CAAC3E,EAAE,CAAC;IACxB,MAAM8E,OAAO,GAAG,CAAC,CAACD,CAAC,EAAElB,WAAW;IAChC,MAAMxC,SAAS,GAAG0D,CAAC,EAAE1D,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACyE,KAAK,CAAC/E,EAAE,CAAC,GAAG;MACdiE,IAAI,EAAEb,MAAM,GAAGrC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAI0D,CAAC,EAAEZ,IAAI,IAAI,IAAK;MAChEa,OAAO;MACP3D;IACF,CAAC;IACDb,GAAG,CAACwE,OAAO,KAAKA,OAAO;IACvB,IAAIxE,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAA4E,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB","ignoreList":[]}
|
|
@@ -1,233 +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
|
-
function newAsyncDataEnvelope(initialData = null, {
|
|
24
|
-
numRefs = 0,
|
|
25
|
-
timestamp = 0
|
|
26
|
-
} = {}) {
|
|
27
|
-
return {
|
|
28
|
-
data: initialData,
|
|
29
|
-
numRefs,
|
|
30
|
-
operationId: '',
|
|
31
|
-
timestamp
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Executes the data loading operation.
|
|
36
|
-
* @param path Data segment path inside the global state.
|
|
37
|
-
* @param loader Data loader.
|
|
38
|
-
* @param globalState The global state instance.
|
|
39
|
-
* @param oldData Optional. Previously fetched data, currently stored in
|
|
40
|
-
* the state, if already fetched by the caller; otherwise, they will be fetched
|
|
41
|
-
* by the load() function itself.
|
|
42
|
-
* @param opIdPrefix operationId prefix to use, which should be
|
|
43
|
-
* 'C' at the client-side (default), or 'S' at the server-side (within SSR
|
|
44
|
-
* context).
|
|
45
|
-
* @return Resolves once the operation is done.
|
|
46
|
-
* @ignore
|
|
47
|
-
*/
|
|
48
|
-
async function load(path, loader, globalState, old,
|
|
49
|
-
// TODO: Should this parameter be just a binary flag (client or server),
|
|
50
|
-
// and UUID always generated inside this function? Or do we need it in
|
|
51
|
-
// the caller methods as well, in some cases (see useAsyncCollection()
|
|
52
|
-
// use case as well).
|
|
53
|
-
operationId = `C${(0, _uuid.v4)()}`) {
|
|
54
|
-
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
55
|
-
/* eslint-disable no-console */
|
|
56
|
-
console.log(`ReactGlobalState: async data (re-)loading. Path: "${path || ''}"`);
|
|
57
|
-
/* eslint-enable no-console */
|
|
58
|
-
}
|
|
59
|
-
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
60
|
-
{
|
|
61
|
-
const prevOperationId = globalState.get(operationIdPath);
|
|
62
|
-
if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);
|
|
63
|
-
}
|
|
64
|
-
globalState.set(operationIdPath, operationId);
|
|
65
|
-
let definedOld = old;
|
|
66
|
-
if (!definedOld) {
|
|
67
|
-
// TODO: Can we improve the typing, to avoid ForceT?
|
|
68
|
-
const e = globalState.get(path);
|
|
69
|
-
definedOld = {
|
|
70
|
-
data: e.data,
|
|
71
|
-
timestamp: e.timestamp
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
const dataOrPromise = loader(definedOld.data, {
|
|
75
|
-
isAborted: () => {
|
|
76
|
-
// TODO: Can we improve the typing, to avoid ForceT?
|
|
77
|
-
const opid = globalState.get(path).operationId;
|
|
78
|
-
return opid !== operationId;
|
|
79
|
-
},
|
|
80
|
-
oldDataTimestamp: definedOld.timestamp,
|
|
81
|
-
setAbortCallback(cb) {
|
|
82
|
-
const opid = globalState.get(path).operationId;
|
|
83
|
-
if (opid !== operationId) {
|
|
84
|
-
throw Error(`Operation #${operationId} has completed already`);
|
|
85
|
-
}
|
|
86
|
-
globalState.setAsyncDataAbortCallback(operationId, cb);
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
let data;
|
|
90
|
-
try {
|
|
91
|
-
data = dataOrPromise instanceof Promise ? await dataOrPromise : dataOrPromise;
|
|
92
|
-
} finally {
|
|
93
|
-
// NOTE: We don't really mean that it hasn't been aborted,
|
|
94
|
-
// the "false" flag rather says we don't need to trigger "on aborted"
|
|
95
|
-
// callback for this operation, if any is registered - just drop it.
|
|
96
|
-
globalState.asyncDataLoadDone(operationId, false);
|
|
97
|
-
}
|
|
98
|
-
const state = globalState.get(path);
|
|
99
|
-
if (operationId === state?.operationId) {
|
|
100
|
-
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
101
|
-
/* eslint-disable no-console */
|
|
102
|
-
console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path || ''}"`);
|
|
103
|
-
console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
|
|
104
|
-
/* eslint-enable no-console */
|
|
105
|
-
}
|
|
106
|
-
globalState.set(path, {
|
|
107
|
-
...state,
|
|
108
|
-
data,
|
|
109
|
-
operationId: '',
|
|
110
|
-
timestamp: Date.now()
|
|
111
|
-
});
|
|
112
|
-
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
113
|
-
/* eslint-disable no-console */
|
|
114
|
-
console.groupEnd();
|
|
115
|
-
/* eslint-enable no-console */
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Resolves asynchronous data, and stores them at given `path` of global
|
|
122
|
-
* state.
|
|
123
|
-
*/
|
|
124
|
-
|
|
125
|
-
function useAsyncData(path, loader, options = {}) {
|
|
126
|
-
const maxage = options.maxage ?? DEFAULT_MAXAGE;
|
|
127
|
-
const refreshAge = options.refreshAge ?? maxage;
|
|
128
|
-
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
129
|
-
|
|
130
|
-
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
131
|
-
// because that way we'll have issues with SSR (see details below).
|
|
132
|
-
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
133
|
-
const state = globalState.get(path, {
|
|
134
|
-
initialValue: newAsyncDataEnvelope()
|
|
135
|
-
});
|
|
136
|
-
const {
|
|
137
|
-
current: heap
|
|
138
|
-
} = (0, _react.useRef)({});
|
|
139
|
-
heap.globalState = globalState;
|
|
140
|
-
heap.path = path;
|
|
141
|
-
heap.loader = loader;
|
|
142
|
-
if (!heap.reload) {
|
|
143
|
-
heap.reload = customLoader => {
|
|
144
|
-
const localLoader = customLoader || heap.loader;
|
|
145
|
-
if (!localLoader || !heap.globalState) throw Error('Internal error');
|
|
146
|
-
return load(heap.path, localLoader, heap.globalState);
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
if (globalState.ssrContext) {
|
|
150
|
-
if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
|
|
151
|
-
globalState.ssrContext.pending.push(load(path, loader, globalState, {
|
|
152
|
-
data: state.data,
|
|
153
|
-
timestamp: state.timestamp
|
|
154
|
-
}, `S${(0, _uuid.v4)()}`));
|
|
155
|
-
}
|
|
156
|
-
} else {
|
|
157
|
-
const {
|
|
158
|
-
disabled
|
|
159
|
-
} = options;
|
|
160
|
-
|
|
161
|
-
// This takes care about the client-side reference counting, and garbage
|
|
162
|
-
// collection.
|
|
163
|
-
//
|
|
164
|
-
// Note: the Rules of Hook below are violated by conditional call to a hook,
|
|
165
|
-
// but as the condition is actually server-side or client-side environment,
|
|
166
|
-
// it is effectively non-conditional at the runtime.
|
|
167
|
-
//
|
|
168
|
-
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
169
|
-
// The same applies to other useEffect() hooks below.
|
|
170
|
-
(0, _react.useEffect)(() => {
|
|
171
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
172
|
-
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
173
|
-
if (!disabled) {
|
|
174
|
-
const numRefs = globalState.get(numRefsPath);
|
|
175
|
-
globalState.set(numRefsPath, numRefs + 1);
|
|
176
|
-
}
|
|
177
|
-
return () => {
|
|
178
|
-
if (!disabled) {
|
|
179
|
-
const state2 = globalState.get(path);
|
|
180
|
-
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
181
|
-
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
182
|
-
/* eslint-disable no-console */
|
|
183
|
-
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
|
|
184
|
-
/* eslint-enable no-console */
|
|
185
|
-
}
|
|
186
|
-
globalState.dropDependencies(path || '');
|
|
187
|
-
globalState.set(path, {
|
|
188
|
-
...state2,
|
|
189
|
-
data: null,
|
|
190
|
-
numRefs: 0,
|
|
191
|
-
timestamp: 0
|
|
192
|
-
});
|
|
193
|
-
} else globalState.set(numRefsPath, state2.numRefs - 1);
|
|
194
|
-
}
|
|
195
|
-
};
|
|
196
|
-
}, [disabled, garbageCollectAge, globalState, path]);
|
|
197
|
-
|
|
198
|
-
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
199
|
-
// special case the otherwise wrong behavior is actually what we need.
|
|
200
|
-
|
|
201
|
-
// Data loading and refreshing.
|
|
202
|
-
(0, _react.useEffect)(() => {
|
|
203
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
204
|
-
if (!disabled) {
|
|
205
|
-
const state2 = globalState.get(path);
|
|
206
|
-
const {
|
|
207
|
-
deps
|
|
208
|
-
} = options;
|
|
209
|
-
if (
|
|
210
|
-
// The hook is called with a list of dependencies, that mismatch
|
|
211
|
-
// dependencies last used to retrieve the data at given path.
|
|
212
|
-
deps && globalState.hasChangedDependencies(path || '', deps)
|
|
213
|
-
|
|
214
|
-
// Data at the path are stale, and are not being loaded.
|
|
215
|
-
|| refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
|
|
216
|
-
if (!deps) globalState.dropDependencies(path || '');
|
|
217
|
-
load(path, loader, globalState, {
|
|
218
|
-
data: state2.data,
|
|
219
|
-
timestamp: state2.timestamp
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
|
|
226
|
-
return {
|
|
227
|
-
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
228
|
-
loading: Boolean(localState.operationId),
|
|
229
|
-
reload: heap.reload,
|
|
230
|
-
timestamp: localState.timestamp
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
//# sourceMappingURL=useAsyncData.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","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 GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => 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\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 async 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): 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<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<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 let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\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 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 * 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<StateT, PathT> =\n 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 if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\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\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\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 globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\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.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n 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\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;;AAqBnC,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;AACA;A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