@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.
@@ -26,9 +26,15 @@ import {
26
26
  type ForceT,
27
27
  type LockT,
28
28
  type TypeLock,
29
+ hash,
29
30
  isDebugMode,
30
31
  } from './utils';
31
32
 
33
+ export type AsyncCollectionT<
34
+ DataT = unknown,
35
+ IdT extends number | string = number | string,
36
+ > = { [id in IdT]?: AsyncDataEnvelopeT<DataT> };
37
+
32
38
  export type AsyncCollectionLoaderT<
33
39
  DataT,
34
40
  IdT extends number | string = number | string,
@@ -67,14 +73,167 @@ type HeapT<
67
73
  IdT extends number | string,
68
74
  > = {
69
75
  // Note: these heap fields are necessary to make reload() a stable function.
70
- globalState?: GlobalState<unknown>;
71
- ids?: IdT[];
72
- path?: null | string;
73
- loader?: AsyncCollectionLoaderT<DataT, IdT>;
74
- reload?: AsyncCollectionReloaderT<DataT, IdT>;
75
- reloadD?: AsyncDataReloaderT<DataT>;
76
+ globalState: GlobalState<unknown>;
77
+ ids: IdT[];
78
+ path: null | string | undefined;
79
+ loader: AsyncCollectionLoaderT<DataT, IdT>;
80
+ reload: AsyncCollectionReloaderT<DataT, IdT>;
81
+ reloadSingle: AsyncDataReloaderT<DataT>;
76
82
  };
77
83
 
84
+ /**
85
+ * GarbageCollector: the piece of logic executed on mounting of
86
+ * an useAsyncCollection() hook, and on update of hook params, to update
87
+ * the state according to the new param values. It increments by 1 `numRefs`
88
+ * counters for the requested collection items.
89
+ */
90
+ function gcOnWithhold<IdT extends number | string>(
91
+ ids: IdT[],
92
+ path: null | string | undefined,
93
+ gs: GlobalState<unknown>,
94
+ ) {
95
+ const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };
96
+
97
+ for (let i = 0; i < ids.length; ++i) {
98
+ const id = ids[i]!;
99
+ let envelope = collection[id];
100
+ if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };
101
+ else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });
102
+ collection[id] = envelope;
103
+ }
104
+
105
+ gs.set<ForceT, AsyncCollectionT>(path, collection);
106
+ }
107
+
108
+ function idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {
109
+ const res = new Set<string>();
110
+ for (let i = 0; i < ids.length; ++i) {
111
+ res.add(ids[i]!.toString());
112
+ }
113
+ return res;
114
+ }
115
+
116
+ /**
117
+ * GarbageCollector: the piece of logic executed on un-mounting of
118
+ * an useAsyncCollection() hook, and on update of hook params, to clean-up
119
+ * after the previous param values. It decrements by 1 `numRefs` counters
120
+ * for previously requested collection items, and also drops from the state
121
+ * stale records.
122
+ */
123
+ function gcOnRelease<IdT extends number | string>(
124
+ ids: IdT[],
125
+ path: null | string | undefined,
126
+ gs: GlobalState<unknown>,
127
+ gcAge: number,
128
+ ) {
129
+ type EnvelopeT = AsyncDataEnvelopeT<unknown>;
130
+
131
+ const entries = Object.entries<EnvelopeT | undefined>(
132
+ gs.get<ForceT, AsyncCollectionT>(path),
133
+ );
134
+
135
+ const now = Date.now();
136
+ const idSet = idsToStringSet(ids);
137
+ const collection: AsyncCollectionT = {};
138
+ for (let i = 0; i < entries.length; ++i) {
139
+ const [id, envelope] = entries[i]!;
140
+
141
+ if (envelope) {
142
+ const toBeReleased = idSet.has(id);
143
+
144
+ let { numRefs } = envelope;
145
+ if (toBeReleased) --numRefs;
146
+
147
+ if (gcAge > now - envelope.timestamp || numRefs > 0) {
148
+ collection[id as IdT] = toBeReleased
149
+ ? { ...envelope, numRefs }
150
+ : envelope;
151
+ } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
152
+ // eslint-disable-next-line no-console
153
+ console.log(
154
+ `useAsyncCollection(): Garbage collected at the path "${
155
+ path}", ID = ${id}`,
156
+ );
157
+ }
158
+ }
159
+ }
160
+
161
+ gs.set<ForceT, AsyncCollectionT>(path, collection);
162
+ }
163
+
164
+ function normalizeIds<IdT extends number | string>(
165
+ idOrIds: IdT | IdT[],
166
+ ): IdT[] {
167
+ if (Array.isArray(idOrIds)) {
168
+ const res = [...idOrIds];
169
+ res.sort();
170
+ return res;
171
+ }
172
+ return [idOrIds];
173
+ }
174
+
175
+ /**
176
+ * Inits/updates, and returns the heap.
177
+ */
178
+ function useHeap<
179
+ DataT,
180
+ IdT extends number | string,
181
+ >(
182
+ ids: IdT[],
183
+ path: null | string | undefined,
184
+ loader: AsyncCollectionLoaderT<DataT, IdT>,
185
+ gs: GlobalState<unknown>,
186
+ ): HeapT<DataT, IdT> {
187
+ const ref = useRef<HeapT<DataT, IdT>>();
188
+
189
+ let heap = ref.current;
190
+
191
+ if (heap) {
192
+ // Update.
193
+ heap.ids = ids;
194
+ heap.path = path;
195
+ heap.loader = loader;
196
+ heap.globalState = gs;
197
+ } else {
198
+ // Initialization.
199
+ const reload = async (
200
+ customLoader?: AsyncCollectionLoaderT<DataT, IdT>,
201
+ ) => {
202
+ const heap2 = ref.current!;
203
+
204
+ const localLoader = customLoader || heap2.loader;
205
+ if (!localLoader || !heap2.globalState || !heap2.ids) {
206
+ throw Error('Internal error');
207
+ }
208
+
209
+ for (let i = 0; i < heap2.ids.length; ++i) {
210
+ const id = heap2.ids[i]!;
211
+ const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
212
+
213
+ // eslint-disable-next-line no-await-in-loop
214
+ await load(
215
+ itemPath,
216
+ (oldData: DataT | null, meta) => localLoader(id, oldData, meta),
217
+ heap2.globalState,
218
+ );
219
+ }
220
+ };
221
+ heap = {
222
+ globalState: gs,
223
+ ids,
224
+ path,
225
+ loader,
226
+ reload,
227
+ reloadSingle: (customLoader) => ref.current!.reload(
228
+ customLoader && ((id, ...args) => customLoader(...args)),
229
+ ),
230
+ };
231
+ ref.current = heap;
232
+ }
233
+
234
+ return heap;
235
+ }
236
+
78
237
  /**
79
238
  * Resolves and stores at the given `path` of the global state elements of
80
239
  * an asynchronous data collection.
@@ -142,53 +301,14 @@ function useAsyncCollection<
142
301
  loader: AsyncCollectionLoaderT<DataT, IdT>,
143
302
  options: UseAsyncDataOptionsT = {},
144
303
  ): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {
145
- const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
146
-
304
+ const ids = normalizeIds(idOrIds);
147
305
  const maxage: number = options.maxage ?? DEFAULT_MAXAGE;
148
306
  const refreshAge: number = options.refreshAge ?? maxage;
149
307
  const garbageCollectAge: number = options.garbageCollectAge ?? maxage;
150
308
 
151
- // To avoid unnecessary work if consumer passes down the same IDs
152
- // in an unstable order.
153
- // TODO: Should we also filter out any duplicates? Or just assume consumer
154
- // knows what he is doing, and won't place duplicates into IDs array?e
155
- ids.sort();
156
-
157
309
  const globalState = getGlobalState();
158
310
 
159
- const { current: heap } = useRef<HeapT<DataT, IdT>>({});
160
-
161
- heap.globalState = globalState;
162
- heap.ids = ids;
163
- heap.path = path;
164
- heap.loader = loader;
165
-
166
- if (!heap.reload) {
167
- heap.reload = async (customLoader?: AsyncCollectionLoaderT<DataT, IdT>) => {
168
- const localLoader = customLoader || heap.loader;
169
- if (!localLoader || !heap.globalState || !heap.ids) {
170
- throw Error('Internal error');
171
- }
172
-
173
- for (let i = 0; i < heap.ids.length; ++i) {
174
- const id = heap.ids[i]!;
175
- const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;
176
-
177
- // eslint-disable-next-line no-await-in-loop
178
- await load(
179
- itemPath,
180
- (oldData: DataT | null, meta) => localLoader(id, oldData, meta),
181
- heap.globalState,
182
- );
183
- }
184
- };
185
- }
186
-
187
- if (!Array.isArray(idOrIds)) {
188
- heap.reloadD = (customLoader) => heap.reload!(
189
- customLoader && ((id, ...args) => customLoader(...args)),
190
- );
191
- }
311
+ const heap = useHeap(ids, path, loader, globalState);
192
312
 
193
313
  // Server-side logic.
194
314
  if (globalState.ssrContext && !options.noSSR) {
@@ -213,56 +333,23 @@ function useAsyncCollection<
213
333
  } else {
214
334
  // Reference-counting & garbage collection.
215
335
 
336
+ const idsHash = hash(ids);
337
+
216
338
  // TODO: Violation of rules of hooks is fine here,
217
339
  // but perhaps it can be refactored to avoid the need for it.
218
340
  useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks
219
- for (let i = 0; i < ids.length; ++i) {
220
- const id = ids[i];
221
- const itemPath = path ? `${path}.${id}` : `${id}`;
222
- const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(
223
- itemPath,
224
- { initialValue: newAsyncDataEnvelope() },
225
- );
226
-
227
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
228
- globalState.set<ForceT, number>(numRefsPath, state.numRefs + 1);
229
- }
230
-
231
- return () => {
232
- for (let i = 0; i < ids.length; ++i) {
233
- const id = ids[i];
234
- const itemPath = path ? `${path}.${id}` : `${id}`;
235
- const state2: AsyncDataEnvelopeT<DataT> = globalState.get<
236
- ForceT, AsyncDataEnvelopeT<DataT>
237
- >(itemPath);
238
- if (
239
- state2.numRefs === 1
240
- && garbageCollectAge < Date.now() - state2.timestamp
241
- ) {
242
- if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
243
- /* eslint-disable no-console */
244
- console.log(
245
- `ReactGlobalState - useAsyncCollection garbage collected at path ${
246
- itemPath || ''
247
- }`,
248
- );
249
- /* eslint-enable no-console */
250
- }
251
- globalState.dropDependencies(itemPath || '');
252
- globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {
253
- ...state2,
254
- data: null,
255
- numRefs: 0,
256
- timestamp: 0,
257
- });
258
- } else {
259
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
260
- globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);
261
- }
262
- }
263
- };
264
- // eslint-disable-next-line react-hooks/exhaustive-deps
265
- }, [garbageCollectAge, globalState, path, ...ids]);
341
+ gcOnWithhold(ids, path, globalState);
342
+ return () => gcOnRelease(ids, path, globalState, garbageCollectAge);
343
+
344
+ // `ids` are represented in the dependencies array by `idsHash` value,
345
+ // as useEffect() hook requires a constant size of dependencies array.
346
+ // eslint-disable-next-line react-hooks/exhaustive-deps
347
+ }, [
348
+ garbageCollectAge,
349
+ globalState,
350
+ idsHash,
351
+ path,
352
+ ]);
266
353
 
267
354
  // NOTE: a bunch of Rules of Hooks ignored belows because in our very
268
355
  // special case the otherwise wrong behavior is actually what we need.
@@ -334,7 +421,7 @@ function useAsyncCollection<
334
421
  return {
335
422
  data: maxage < Date.now() - timestamp ? null : (e?.data ?? null),
336
423
  loading: !!e?.operationId,
337
- reload: heap.reloadD!,
424
+ reload: heap.reloadSingle!,
338
425
  timestamp,
339
426
  };
340
427
  }
package/src/utils.ts CHANGED
@@ -76,6 +76,7 @@ const cloneDeepBailKeys = new Set<string>();
76
76
  */
77
77
  export function cloneDeepForLog<T>(value: T, key: string = ''): T {
78
78
  if (cloneDeepBailKeys.has(key)) {
79
+ // eslint-disable-next-line no-console
79
80
  console.warn(`The logged value won't be clonned (key "${key}").`);
80
81
  return value;
81
82
  }
@@ -84,9 +85,32 @@ export function cloneDeepForLog<T>(value: T, key: string = ''): T {
84
85
  const res = cloneDeep(value);
85
86
  const time = Date.now() - start;
86
87
  if (time > 300) {
88
+ // eslint-disable-next-line no-console
87
89
  console.warn(`${time}ms spent to clone the logged value (key "${key}").`);
88
90
  cloneDeepBailKeys.add(key);
89
91
  }
90
92
 
91
93
  return res;
92
94
  }
95
+
96
+ /**
97
+ * Converts given value to an escaped string. For now, we are good with the most
98
+ * trivial escape logic:
99
+ * - '%' characters are replaced by '%0' code pair;
100
+ * - '/' characters are replaced by '%1' code pair.
101
+ */
102
+ export function escape(x: number | string): string {
103
+ return typeof x === 'string'
104
+ ? x.replace(/%/g, '%0').replace(/\//g, '%1')
105
+ : x.toString();
106
+ }
107
+
108
+ /**
109
+ * Hashes given string array. For our current needs we are fine to go with
110
+ * the most trivial implementation, which probably should not be called "hash"
111
+ * in the strict sense: we just escape each given string to not include '/'
112
+ * characters, and then we join all those strings using '/' as the separator.
113
+ */
114
+ export function hash(items: Array<number | string>): string {
115
+ return items.map(escape).join('/');
116
+ }