@dr.pogodin/react-global-state 0.16.0 → 0.17.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/build/common/index.js.map +1 -1
- package/build/common/useAsyncCollection.js +125 -67
- package/build/common/useAsyncCollection.js.map +1 -1
- package/build/common/utils.js +24 -0
- package/build/common/utils.js.map +1 -1
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js +130 -73
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/utils.js +22 -0
- package/build/module/utils.js.map +1 -1
- package/build/types/index.d.ts +3 -3
- package/build/types/useAsyncCollection.d.ts +4 -1
- package/build/types/utils.d.ts +14 -0
- package/package.json +3 -3
- package/src/index.ts +3 -1
- package/src/useAsyncCollection.ts +182 -95
- package/src/utils.ts +24 -0
|
@@ -7,7 +7,125 @@ import { v4 as uuid } from 'uuid';
|
|
|
7
7
|
import { getGlobalState } from "./GlobalStateProvider";
|
|
8
8
|
import { DEFAULT_MAXAGE, load, newAsyncDataEnvelope } from "./useAsyncData";
|
|
9
9
|
import useGlobalState from "./useGlobalState";
|
|
10
|
-
import { isDebugMode } from "./utils";
|
|
10
|
+
import { hash, isDebugMode } from "./utils";
|
|
11
|
+
/**
|
|
12
|
+
* GarbageCollector: the piece of logic executed on mounting of
|
|
13
|
+
* an useAsyncCollection() hook, and on update of hook params, to update
|
|
14
|
+
* the state according to the new param values. It increments by 1 `numRefs`
|
|
15
|
+
* counters for the requested collection items.
|
|
16
|
+
*/
|
|
17
|
+
function gcOnWithhold(ids, path, gs) {
|
|
18
|
+
const collection = {
|
|
19
|
+
...gs.get(path)
|
|
20
|
+
};
|
|
21
|
+
for (let i = 0; i < ids.length; ++i) {
|
|
22
|
+
const id = ids[i];
|
|
23
|
+
let envelope = collection[id];
|
|
24
|
+
if (envelope) envelope = {
|
|
25
|
+
...envelope,
|
|
26
|
+
numRefs: 1 + envelope.numRefs
|
|
27
|
+
};else envelope = newAsyncDataEnvelope(null, {
|
|
28
|
+
numRefs: 1
|
|
29
|
+
});
|
|
30
|
+
collection[id] = envelope;
|
|
31
|
+
}
|
|
32
|
+
gs.set(path, collection);
|
|
33
|
+
}
|
|
34
|
+
function idsToStringSet(ids) {
|
|
35
|
+
const res = new Set();
|
|
36
|
+
for (let i = 0; i < ids.length; ++i) {
|
|
37
|
+
res.add(ids[i].toString());
|
|
38
|
+
}
|
|
39
|
+
return res;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* GarbageCollector: the piece of logic executed on un-mounting of
|
|
44
|
+
* an useAsyncCollection() hook, and on update of hook params, to clean-up
|
|
45
|
+
* after the previous param values. It decrements by 1 `numRefs` counters
|
|
46
|
+
* for previously requested collection items, and also drops from the state
|
|
47
|
+
* stale records.
|
|
48
|
+
*/
|
|
49
|
+
function gcOnRelease(ids, path, gs, gcAge) {
|
|
50
|
+
const entries = Object.entries(gs.get(path));
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
const idSet = idsToStringSet(ids);
|
|
53
|
+
const collection = {};
|
|
54
|
+
for (let i = 0; i < entries.length; ++i) {
|
|
55
|
+
const [id, envelope] = entries[i];
|
|
56
|
+
if (envelope) {
|
|
57
|
+
const toBeReleased = idSet.has(id);
|
|
58
|
+
let {
|
|
59
|
+
numRefs
|
|
60
|
+
} = envelope;
|
|
61
|
+
if (toBeReleased) --numRefs;
|
|
62
|
+
if (gcAge > now - envelope.timestamp || numRefs > 0) {
|
|
63
|
+
collection[id] = toBeReleased ? {
|
|
64
|
+
...envelope,
|
|
65
|
+
numRefs
|
|
66
|
+
} : envelope;
|
|
67
|
+
} else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
68
|
+
// eslint-disable-next-line no-console
|
|
69
|
+
console.log(`useAsyncCollection(): Garbage collected at the path "${path}", ID = ${id}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
gs.set(path, collection);
|
|
74
|
+
}
|
|
75
|
+
function normalizeIds(idOrIds) {
|
|
76
|
+
if (Array.isArray(idOrIds)) {
|
|
77
|
+
const res = [...idOrIds];
|
|
78
|
+
res.sort();
|
|
79
|
+
return res;
|
|
80
|
+
}
|
|
81
|
+
return [idOrIds];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Inits/updates, and returns the heap.
|
|
86
|
+
*/
|
|
87
|
+
function useHeap(ids, path, loader, gs) {
|
|
88
|
+
const ref = useRef();
|
|
89
|
+
let heap = ref.current;
|
|
90
|
+
if (heap) {
|
|
91
|
+
// Update.
|
|
92
|
+
heap.ids = ids;
|
|
93
|
+
heap.path = path;
|
|
94
|
+
heap.loader = loader;
|
|
95
|
+
heap.globalState = gs;
|
|
96
|
+
} else {
|
|
97
|
+
// Initialization.
|
|
98
|
+
const reload = async customLoader => {
|
|
99
|
+
const heap2 = ref.current;
|
|
100
|
+
const localLoader = customLoader || heap2.loader;
|
|
101
|
+
if (!localLoader || !heap2.globalState || !heap2.ids) {
|
|
102
|
+
throw Error('Internal error');
|
|
103
|
+
}
|
|
104
|
+
for (let i = 0; i < heap2.ids.length; ++i) {
|
|
105
|
+
const id = heap2.ids[i];
|
|
106
|
+
const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
|
|
107
|
+
|
|
108
|
+
// eslint-disable-next-line no-await-in-loop
|
|
109
|
+
await load(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
heap = {
|
|
113
|
+
globalState: gs,
|
|
114
|
+
ids,
|
|
115
|
+
path,
|
|
116
|
+
loader,
|
|
117
|
+
reload,
|
|
118
|
+
reloadSingle: customLoader => ref.current.reload(customLoader && function (id) {
|
|
119
|
+
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
120
|
+
args[_key - 1] = arguments[_key];
|
|
121
|
+
}
|
|
122
|
+
return customLoader(...args);
|
|
123
|
+
})
|
|
124
|
+
};
|
|
125
|
+
ref.current = heap;
|
|
126
|
+
}
|
|
127
|
+
return heap;
|
|
128
|
+
}
|
|
11
129
|
|
|
12
130
|
/**
|
|
13
131
|
* Resolves and stores at the given `path` of the global state elements of
|
|
@@ -20,47 +138,12 @@ import { isDebugMode } from "./utils";
|
|
|
20
138
|
function useAsyncCollection(idOrIds, path, loader) {
|
|
21
139
|
var _options$maxage, _options$refreshAge, _options$garbageColle;
|
|
22
140
|
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
23
|
-
const ids =
|
|
141
|
+
const ids = normalizeIds(idOrIds);
|
|
24
142
|
const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
|
|
25
143
|
const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
|
|
26
144
|
const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
|
|
27
|
-
|
|
28
|
-
// To avoid unnecessary work if consumer passes down the same IDs
|
|
29
|
-
// in an unstable order.
|
|
30
|
-
// TODO: Should we also filter out any duplicates? Or just assume consumer
|
|
31
|
-
// knows what he is doing, and won't place duplicates into IDs array?e
|
|
32
|
-
ids.sort();
|
|
33
145
|
const globalState = getGlobalState();
|
|
34
|
-
const
|
|
35
|
-
current: heap
|
|
36
|
-
} = useRef({});
|
|
37
|
-
heap.globalState = globalState;
|
|
38
|
-
heap.ids = ids;
|
|
39
|
-
heap.path = path;
|
|
40
|
-
heap.loader = loader;
|
|
41
|
-
if (!heap.reload) {
|
|
42
|
-
heap.reload = async customLoader => {
|
|
43
|
-
const localLoader = customLoader || heap.loader;
|
|
44
|
-
if (!localLoader || !heap.globalState || !heap.ids) {
|
|
45
|
-
throw Error('Internal error');
|
|
46
|
-
}
|
|
47
|
-
for (let i = 0; i < heap.ids.length; ++i) {
|
|
48
|
-
const id = heap.ids[i];
|
|
49
|
-
const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;
|
|
50
|
-
|
|
51
|
-
// eslint-disable-next-line no-await-in-loop
|
|
52
|
-
await load(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap.globalState);
|
|
53
|
-
}
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
if (!Array.isArray(idOrIds)) {
|
|
57
|
-
heap.reloadD = customLoader => heap.reload(customLoader && function (id) {
|
|
58
|
-
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
59
|
-
args[_key - 1] = arguments[_key];
|
|
60
|
-
}
|
|
61
|
-
return customLoader(...args);
|
|
62
|
-
});
|
|
63
|
-
}
|
|
146
|
+
const heap = useHeap(ids, path, loader, globalState);
|
|
64
147
|
|
|
65
148
|
// Server-side logic.
|
|
66
149
|
if (globalState.ssrContext && !options.noSSR) {
|
|
@@ -88,45 +171,19 @@ function useAsyncCollection(idOrIds, path, loader) {
|
|
|
88
171
|
} else {
|
|
89
172
|
// Reference-counting & garbage collection.
|
|
90
173
|
|
|
174
|
+
const idsHash = hash(ids);
|
|
175
|
+
|
|
91
176
|
// TODO: Violation of rules of hooks is fine here,
|
|
92
177
|
// but perhaps it can be refactored to avoid the need for it.
|
|
93
178
|
useEffect(() => {
|
|
94
179
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
});
|
|
101
|
-
const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
|
|
102
|
-
globalState.set(numRefsPath, state.numRefs + 1);
|
|
103
|
-
}
|
|
104
|
-
return () => {
|
|
105
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
106
|
-
const id = ids[i];
|
|
107
|
-
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
108
|
-
const state2 = globalState.get(itemPath);
|
|
109
|
-
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
110
|
-
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
111
|
-
/* eslint-disable no-console */
|
|
112
|
-
console.log(`ReactGlobalState - useAsyncCollection garbage collected at path ${itemPath || ''}`);
|
|
113
|
-
/* eslint-enable no-console */
|
|
114
|
-
}
|
|
115
|
-
globalState.dropDependencies(itemPath || '');
|
|
116
|
-
globalState.set(itemPath, {
|
|
117
|
-
...state2,
|
|
118
|
-
data: null,
|
|
119
|
-
numRefs: 0,
|
|
120
|
-
timestamp: 0
|
|
121
|
-
});
|
|
122
|
-
} else {
|
|
123
|
-
const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
|
|
124
|
-
globalState.set(numRefsPath, state2.numRefs - 1);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
};
|
|
180
|
+
gcOnWithhold(ids, path, globalState);
|
|
181
|
+
return () => gcOnRelease(ids, path, globalState, garbageCollectAge);
|
|
182
|
+
|
|
183
|
+
// `ids` are represented in the dependencies array by `idsHash` value,
|
|
184
|
+
// as useEffect() hook requires a constant size of dependencies array.
|
|
128
185
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
129
|
-
}, [garbageCollectAge, globalState,
|
|
186
|
+
}, [garbageCollectAge, globalState, idsHash, path]);
|
|
130
187
|
|
|
131
188
|
// NOTE: a bunch of Rules of Hooks ignored belows because in our very
|
|
132
189
|
// special case the otherwise wrong behavior is actually what we need.
|
|
@@ -189,7 +246,7 @@ function useAsyncCollection(idOrIds, path, loader) {
|
|
|
189
246
|
return {
|
|
190
247
|
data: maxage < Date.now() - timestamp ? null : (_e$data = e === null || e === void 0 ? void 0 : e.data) !== null && _e$data !== void 0 ? _e$data : null,
|
|
191
248
|
loading: !!(e !== null && e !== void 0 && e.operationId),
|
|
192
|
-
reload: heap.
|
|
249
|
+
reload: heap.reloadSingle,
|
|
193
250
|
timestamp
|
|
194
251
|
};
|
|
195
252
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","isDebugMode","useAsyncCollection","idOrIds","path","loader","_options$maxage","_options$refreshAge","_options$garbageColle","options","arguments","length","undefined","ids","Array","isArray","maxage","refreshAge","garbageCollectAge","sort","globalState","current","heap","reload","customLoader","localLoader","Error","i","id","itemPath","oldData","meta","reloadD","_len","args","_key","ssrContext","noSSR","operationId","state","get","initialValue","timestamp","pending","push","_len2","_key2","data","numRefsPath","set","numRefs","state2","Date","now","process","env","NODE_ENV","console","log","dropDependencies","loadTriggeredForIds","Set","deps","hasChangedDependencies","charAt","add","_len3","_key3","has","localState","_e$timestamp","_e$data","e","loading","res","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"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 isDebugMode,\n} from './utils';\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 }) => 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;\n loader?: AsyncCollectionLoaderT<DataT, IdT>;\n reload?: AsyncCollectionReloaderT<DataT, IdT>;\n reloadD?: AsyncDataReloaderT<DataT>;\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 = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // To avoid unnecessary work if consumer passes down the same IDs\n // in an unstable order.\n // TODO: Should we also filter out any duplicates? Or just assume consumer\n // knows what he is doing, and won't place duplicates into IDs array?e\n ids.sort();\n\n const globalState = getGlobalState();\n\n const { current: heap } = useRef<HeapT<DataT, IdT>>({});\n\n heap.globalState = globalState;\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = async (customLoader?: AsyncCollectionLoaderT<DataT, IdT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState || !heap.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap.ids.length; ++i) {\n const id = heap.ids[i]!;\n const itemPath = heap.path ? `${heap.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 heap.globalState,\n );\n }\n };\n }\n\n if (!Array.isArray(idOrIds)) {\n heap.reloadD = (customLoader) => heap.reload!(\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n }\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 // 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 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>>(\n itemPath,\n { initialValue: newAsyncDataEnvelope() },\n );\n\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state.numRefs + 1);\n }\n\n return () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i];\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>\n >(itemPath);\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 - useAsyncCollection garbage collected at path ${\n itemPath || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(itemPath || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [garbageCollectAge, globalState, path, ...ids]);\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 const loadTriggeredForIds = new Set<IdT>();\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 const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n loadTriggeredForIds.add(id);\n // eslint-disable-next-line no-await-in-loop\n await load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n })();\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n const { deps } = options;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n if (\n deps\n && globalState.hasChangedDependencies(itemPath || '', deps)\n && !loadTriggeredForIds.has(id)\n ) {\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: null | DataT, meta) => loader(id, oldData, meta),\n globalState,\n );\n }\n }\n })();\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\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.reloadD!,\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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,WAAW;;AAiDb;AACA;AACA;AACA;;AAoDA;AACA;AACA;AACA,SAASC,kBAAkBA,CAIzBC,OAAoB,EACpBC,IAA+B,EAC/BC,MAA0C,EAEoB;EAAA,IAAAC,eAAA,EAAAC,mBAAA,EAAAC,qBAAA;EAAA,IAD9DC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,GAAG,GAAGC,KAAK,CAACC,OAAO,CAACZ,OAAO,CAAC,GAAGA,OAAO,GAAG,CAACA,OAAO,CAAC;EAExD,MAAMa,MAAc,IAAAV,eAAA,GAAGG,OAAO,CAACO,MAAM,cAAAV,eAAA,cAAAA,eAAA,GAAIT,cAAc;EACvD,MAAMoB,UAAkB,IAAAV,mBAAA,GAAGE,OAAO,CAACQ,UAAU,cAAAV,mBAAA,cAAAA,mBAAA,GAAIS,MAAM;EACvD,MAAME,iBAAyB,IAAAV,qBAAA,GAAGC,OAAO,CAACS,iBAAiB,cAAAV,qBAAA,cAAAA,qBAAA,GAAIQ,MAAM;;EAErE;EACA;EACA;EACA;EACAH,GAAG,CAACM,IAAI,CAAC,CAAC;EAEV,MAAMC,WAAW,GAAGxB,cAAc,CAAC,CAAC;EAEpC,MAAM;IAAEyB,OAAO,EAAEC;EAAK,CA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gB,CAAC,EAAE;IAAA,IAAAmD,aAAA,EAAAC,QAAA;IACnC,MAAMnD,EAAE,GAAGf,GAAG,CAACc,CAAC,CAAE;IAClB,MAAM6C,CAAC,GAAGH,UAAU,CAACzC,EAAE,CAAC;IACxB,MAAM6C,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAElC,WAAW;IAChC,MAAMI,SAAS,IAAAoC,aAAA,GAAGN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAE9B,SAAS,cAAAoC,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCJ,GAAG,CAACC,KAAK,CAAC/C,EAAE,CAAC,GAAG;MACdmB,IAAI,EAAE/B,MAAM,GAAGoC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGX,SAAS,GAAG,IAAI,IAAAqC,QAAA,GAAIP,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEzB,IAAI,cAAAgC,QAAA,cAAAA,QAAA,GAAI,IAAK;MAChEN,OAAO;MACP/B;IACF,CAAC;IACDgC,GAAG,CAACD,OAAO,KAAXC,GAAG,CAACD,OAAO,GAAKA,OAAO;IACvB,IAAIC,GAAG,CAAChC,SAAS,GAAGA,SAAS,EAAEgC,GAAG,CAAChC,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOgC,GAAG;AACZ;AAEA,eAAexE,kBAAkB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","i","length","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","sort","useHeap","loader","ref","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","oldData","meta","reloadSingle","_len","arguments","args","_key","useAsyncCollection","_options$maxage","_options$refreshAge","_options$garbageColle","options","undefined","maxage","refreshAge","garbageCollectAge","ssrContext","noSSR","operationId","state","initialValue","pending","push","_len2","_key2","data","idsHash","loadTriggeredForIds","state2","deps","hasChangedDependencies","charAt","dropDependencies","_len3","_key3","localState","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"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 }) => 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>>();\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 const loadTriggeredForIds = new Set<IdT>();\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 const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n loadTriggeredForIds.add(id);\n // eslint-disable-next-line no-await-in-loop\n await load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n })();\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n const { deps } = options;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n if (\n deps\n && globalState.hasChangedDependencies(itemPath || '', deps)\n && !loadTriggeredForIds.has(id)\n ) {\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: null | DataT, meta) => loader(id, oldData, meta),\n globalState,\n );\n }\n }\n })();\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,IAAI,EACJC,WAAW;AAsDb;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,YAAYA,CACnBC,GAAU,EACVC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nC/E,GAAG,CAAC4E,KAAK,CAACjF,EAAE,CAAC,GAAG;MACdkE,IAAI,EAAEZ,MAAM,GAAGxC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,IAAAmE,QAAA,GAAIN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEb,IAAI,cAAAmB,QAAA,cAAAA,QAAA,GAAI,IAAK;MAChEL,OAAO;MACP9D;IACF,CAAC;IACDb,GAAG,CAAC2E,OAAO,KAAX3E,GAAG,CAAC2E,OAAO,GAAKA,OAAO;IACvB,IAAI3E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe2C,kBAAkB","ignoreList":[]}
|
package/build/module/utils.js
CHANGED
|
@@ -47,6 +47,7 @@ const cloneDeepBailKeys = new Set();
|
|
|
47
47
|
export function cloneDeepForLog(value) {
|
|
48
48
|
let key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
|
|
49
49
|
if (cloneDeepBailKeys.has(key)) {
|
|
50
|
+
// eslint-disable-next-line no-console
|
|
50
51
|
console.warn(`The logged value won't be clonned (key "${key}").`);
|
|
51
52
|
return value;
|
|
52
53
|
}
|
|
@@ -54,9 +55,30 @@ export function cloneDeepForLog(value) {
|
|
|
54
55
|
const res = cloneDeep(value);
|
|
55
56
|
const time = Date.now() - start;
|
|
56
57
|
if (time > 300) {
|
|
58
|
+
// eslint-disable-next-line no-console
|
|
57
59
|
console.warn(`${time}ms spent to clone the logged value (key "${key}").`);
|
|
58
60
|
cloneDeepBailKeys.add(key);
|
|
59
61
|
}
|
|
60
62
|
return res;
|
|
61
63
|
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Converts given value to an escaped string. For now, we are good with the most
|
|
67
|
+
* trivial escape logic:
|
|
68
|
+
* - '%' characters are replaced by '%0' code pair;
|
|
69
|
+
* - '/' characters are replaced by '%1' code pair.
|
|
70
|
+
*/
|
|
71
|
+
export function escape(x) {
|
|
72
|
+
return typeof x === 'string' ? x.replace(/%/g, '%0').replace(/\//g, '%1') : x.toString();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Hashes given string array. For our current needs we are fine to go with
|
|
77
|
+
* the most trivial implementation, which probably should not be called "hash"
|
|
78
|
+
* in the strict sense: we just escape each given string to not include '/'
|
|
79
|
+
* characters, and then we join all those strings using '/' as the separator.
|
|
80
|
+
*/
|
|
81
|
+
export function hash(items) {
|
|
82
|
+
return items.map(escape).join('/');
|
|
83
|
+
}
|
|
62
84
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","arguments","length","undefined","has","console","warn","start","Date","now","res","time","add"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType, cloneDeep } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n"],"mappings":"AAAA,SAA4BA,SAAS,QAAQ,QAAQ;;AAIrD;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF;AAEA,MAAMC,iBAAiB,GAAG,IAAIC,GAAG,CAAS,CAAC;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAAIC,KAAQ,EAAuB;EAAA,IAArBC,GAAW,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,EAAE;EAC3D,IAAIL,iBAAiB,CAACQ,GAAG,CAACJ,GAAG,CAAC,EAAE;
|
|
1
|
+
{"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","arguments","length","undefined","has","console","warn","start","Date","now","res","time","add","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType, cloneDeep } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');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EAAU;EACjD,OAAO,OAAOA,CAAC,KAAK,QAAQ,GACxBA,CAAC,CAACC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,GAC1CD,CAAC,CAACE,QAAQ,CAAC,CAAC;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
|
package/build/types/index.d.ts
CHANGED
|
@@ -2,12 +2,12 @@ import GlobalState from './GlobalState';
|
|
|
2
2
|
import GlobalStateProvider, { getGlobalState, getSsrContext } from './GlobalStateProvider';
|
|
3
3
|
import SsrContext from './SsrContext';
|
|
4
4
|
import useAsyncCollection, { type UseAsyncCollectionI, type UseAsyncCollectionResT } from './useAsyncCollection';
|
|
5
|
-
import { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncDataI, type UseAsyncDataResT, newAsyncDataEnvelope, useAsyncData } from './useAsyncData';
|
|
5
|
+
import { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncDataI, type UseAsyncDataOptionsT, type UseAsyncDataResT, newAsyncDataEnvelope, useAsyncData } from './useAsyncData';
|
|
6
6
|
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
7
|
-
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
7
|
+
export type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';
|
|
8
8
|
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
9
9
|
export type { ForceT, ValueOrInitializerT } from './utils';
|
|
10
|
-
export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncCollectionResT, type UseAsyncDataResT, getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState, };
|
|
10
|
+
export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncCollectionResT, type UseAsyncDataOptionsT, type UseAsyncDataResT, getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState, };
|
|
11
11
|
interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
|
|
12
12
|
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
13
13
|
getSsrContext: typeof getSsrContext<SsrContextT>;
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Loads and uses item(s) in an async collection.
|
|
3
3
|
*/
|
|
4
|
-
import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
4
|
+
import { type AsyncDataEnvelopeT, type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
5
5
|
import { type ForceT, type LockT, type TypeLock } from './utils';
|
|
6
|
+
export type AsyncCollectionT<DataT = unknown, IdT extends number | string = number | string> = {
|
|
7
|
+
[id in IdT]?: AsyncDataEnvelopeT<DataT>;
|
|
8
|
+
};
|
|
6
9
|
export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number | string> = (id: IdT, oldData: null | DataT, meta: {
|
|
7
10
|
isAborted: () => boolean;
|
|
8
11
|
oldDataTimestamp: number;
|
package/build/types/utils.d.ts
CHANGED
|
@@ -40,4 +40,18 @@ export declare function isDebugMode(): boolean;
|
|
|
40
40
|
* development versions of the app due to the logging overhead).
|
|
41
41
|
*/
|
|
42
42
|
export declare function cloneDeepForLog<T>(value: T, key?: string): T;
|
|
43
|
+
/**
|
|
44
|
+
* Converts given value to an escaped string. For now, we are good with the most
|
|
45
|
+
* trivial escape logic:
|
|
46
|
+
* - '%' characters are replaced by '%0' code pair;
|
|
47
|
+
* - '/' characters are replaced by '%1' code pair.
|
|
48
|
+
*/
|
|
49
|
+
export declare function escape(x: number | string): string;
|
|
50
|
+
/**
|
|
51
|
+
* Hashes given string array. For our current needs we are fine to go with
|
|
52
|
+
* the most trivial implementation, which probably should not be called "hash"
|
|
53
|
+
* in the strict sense: we just escape each given string to not include '/'
|
|
54
|
+
* characters, and then we join all those strings using '/' as the separator.
|
|
55
|
+
*/
|
|
56
|
+
export declare function hash(items: Array<number | string>): string;
|
|
43
57
|
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
5
|
"main": "./build/common/index.js",
|
|
6
6
|
"react-native": "src/index.ts",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"eslint-config-airbnb-typescript": "^18.0.0",
|
|
75
75
|
"eslint-import-resolver-babel-module": "^5.3.2",
|
|
76
76
|
"eslint-plugin-import": "^2.29.1",
|
|
77
|
-
"eslint-plugin-jest": "^28.
|
|
77
|
+
"eslint-plugin-jest": "^28.8.0",
|
|
78
78
|
"eslint-plugin-jsx-a11y": "^6.9.0",
|
|
79
79
|
"eslint-plugin-react": "^7.35.0",
|
|
80
80
|
"eslint-plugin-react-hooks": "^4.6.2",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"rimraf": "^6.0.1",
|
|
85
85
|
"tstyche": "^2.1.1",
|
|
86
86
|
"typescript": "^5.5.4",
|
|
87
|
-
"typescript-eslint": "^8.0.
|
|
87
|
+
"typescript-eslint": "^8.0.1"
|
|
88
88
|
},
|
|
89
89
|
"peerDependencies": {
|
|
90
90
|
"react": "^18.3.1",
|
package/src/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
type AsyncDataLoaderT,
|
|
18
18
|
type AsyncDataReloaderT,
|
|
19
19
|
type UseAsyncDataI,
|
|
20
|
+
type UseAsyncDataOptionsT,
|
|
20
21
|
type UseAsyncDataResT,
|
|
21
22
|
newAsyncDataEnvelope,
|
|
22
23
|
useAsyncData,
|
|
@@ -24,7 +25,7 @@ import {
|
|
|
24
25
|
|
|
25
26
|
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
26
27
|
|
|
27
|
-
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
28
|
+
export type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';
|
|
28
29
|
|
|
29
30
|
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
30
31
|
|
|
@@ -35,6 +36,7 @@ export {
|
|
|
35
36
|
type AsyncDataLoaderT,
|
|
36
37
|
type AsyncDataReloaderT,
|
|
37
38
|
type UseAsyncCollectionResT,
|
|
39
|
+
type UseAsyncDataOptionsT,
|
|
38
40
|
type UseAsyncDataResT,
|
|
39
41
|
getGlobalState,
|
|
40
42
|
getSsrContext,
|