@dr.pogodin/react-global-state 0.16.1 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,7 @@ var _lodash = require("lodash");
8
8
  var _utils = require("./utils");
9
9
  const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
10
10
  class GlobalState {
11
+ #asyncDataAbortCallbacks = {};
11
12
  #dependencies = {};
12
13
  #initialState;
13
14
 
@@ -47,6 +48,24 @@ class GlobalState {
47
48
  }
48
49
  }
49
50
 
51
+ /**
52
+ * Returns the number of currently registered async data abort callbacks,
53
+ * just for the sake of testing the library.
54
+ */
55
+ get numAsyncDataAbortCallbacks() {
56
+ return Object.keys(this.#asyncDataAbortCallbacks).length;
57
+ }
58
+
59
+ /**
60
+ * If `aborted` is "true" and there is an abort callback registered for
61
+ * the specified operation, it triggers the callback. Then, in any case,
62
+ * it drops the callback.
63
+ */
64
+ asyncDataLoadDone(opid, aborted) {
65
+ if (aborted) this.#asyncDataAbortCallbacks[opid]?.();
66
+ delete this.#asyncDataAbortCallbacks[opid];
67
+ }
68
+
50
69
  /**
51
70
  * Drops the record of dependencies, if any, for the given path.
52
71
  */
@@ -59,6 +78,11 @@ class GlobalState {
59
78
  * the given `path`. If they are, `deps` are recorded as the new deps for
60
79
  * the `path`, and also the array is frozen, to prevent it from being
61
80
  * modified.
81
+ *
82
+ * TODO: This may not work as expected if path string is not normalized,
83
+ * and the for the same path different alternative ways to spell it down
84
+ * are used. We should normalize given path here, I guess, or on a higher
85
+ * level in the logic?
62
86
  */
63
87
  hasChangedDependencies(path, deps) {
64
88
  const prevDeps = this.#dependencies[path];
@@ -111,6 +135,14 @@ class GlobalState {
111
135
  }
112
136
  }
113
137
 
138
+ /**
139
+ * Registers an abort callback for an async data retrieval operation with
140
+ * the given operation ID. Throws if already registered.
141
+ */
142
+ setAsyncDataAbortCallback(opid, cb) {
143
+ this.#asyncDataAbortCallbacks[opid] = cb;
144
+ }
145
+
114
146
  /**
115
147
  * Sets entire state, the same way as .set(null, value) would do.
116
148
  * @param value
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalState.js","names":["_lodash","require","_utils","ERR_NO_SSR_WATCH","GlobalState","dependencies","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeepForLog","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","isFunction","setEntireState","notifyStateUpdate","value","p","setTimeout","get","isNil","res","set","root","segIdx","pos","pathSegments","toPath","seg","next","Array","isArray","isObject","slice","unWatch","callback","Error","indexOf","pop","watch","push","exports","default"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #dependencies: { [key: string]: Readonly<any[]> } = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n */\n hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]!();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAWA,IAAAC,MAAA,GAAAD,OAAA;AAWA,MAAME,gBAAgB,GAAG,gDAAgD;AAO1D,MAAMC,WAAW,CAG9B;EAGA,CAACC,YAAY,GAAuC,CAAC,CAAC;EAEtD,CAACC,YAAY;;EAEb;EACA;EACA;EACA;EACA,CAACC,QAAQ,GAAgB,EAAE;EAE3B,CAACC,cAAc;EAEf,CAACC,YAAY;;EAEb;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTJ,YAAoB,EACpBK,UAAwB,EACxB;IACA,IAAI,CAAC,CAACF,YAAY,GAAGH,YAAY;IACjC,IAAI,CAAC,CAACA,YAAY,GAAGA,YAAY;IAEjC,IAAIK,UAAU,EAAE;MACd;MACAA,UAAU,CAACC,KAAK,GAAG,KAAK;MACxBD,UAAU,CAACE,OAAO,GAAG,EAAE;MACvBF,UAAU,CAACG,KAAK,GAAG,IAAI,CAAC,CAACL,YAAY;MACrC;;MAEA,IAAI,CAACE,UAAU,GAAGA,UAAU;IAC9B;IAEA,IAAII,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SSR_WATCH","GlobalState","asyncDataAbortCallbacks","dependencies","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeepForLog","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","freeze","getEntireState","opts","undefined","initialValue","iv","isFunction","setEntireState","notifyStateUpdate","value","p","setTimeout","setAsyncDataAbortCallback","cb","get","isNil","res","set","root","segIdx","pos","pathSegments","toPath","seg","next","Array","isArray","isObject","slice","unWatch","callback","Error","indexOf","pop","watch","push","exports","default"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks: Record<string, () => void> = {};\n\n #dependencies: { [key: string]: Readonly<any[]> } = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return Object.keys(this.#asyncDataAbortCallbacks).length;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean) {\n if (aborted) this.#asyncDataAbortCallbacks[opid]?.();\n delete this.#asyncDataAbortCallbacks[opid];\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]!();\n }\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void) {\n this.#asyncDataAbortCallbacks[opid] = cb;\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAWA,IAAAC,MAAA,GAAAD,OAAA;AAWA,MAAME,gBAAgB,GAAG,gDAAgD;AAO1D,MAAMC,WAAW,CAG9B;EAGA,CAACC,uBAAu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AAM,CAAC,CAAE,GAAGV,KAAK;MACpC;MAEA,IAAI,CAAC,CAACvC,YAAY,GAAGgD,IAAI,CAAC3C,KAAK;MAE/B,IAAI,CAACiC,iBAAiB,CAACd,IAAI,EAAEe,KAAK,CAAC;IACrC;IACA,OAAOA,KAAK;EACd;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;EACEoB,OAAOA,CAACC,QAAmB,EAAE;IAC3B,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACpE,gBAAgB,CAAC;IAEtD,MAAMK,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,MAAMoD,GAAG,GAAGpD,QAAQ,CAACgE,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIV,GAAG,IAAI,CAAC,EAAE;MACZpD,QAAQ,CAACoD,GAAG,CAAC,GAAGpD,QAAQ,CAACA,QAAQ,CAACqB,MAAM,GAAG,CAAC,CAAE;MAC9CrB,QAAQ,CAACiE,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACpE,gBAAgB,CAAC;IAEtD,MAAMK,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,IAAIA,QAAQ,CAACgE,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClC9D,QAAQ,CAACmE,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF;AAACM,OAAA,CAAAC,OAAA,GAAAzE,WAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAL,OAAA;AAWA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAAwE,SAAAO,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,OAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,EAAAc,CAAA,SAAAG,CAAA,GAAAP,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAG,CAAA,KAAAA,CAAA,CAAAV,GAAA,IAAAU,CAAA,CAAAC,GAAA,IAAAP,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAG,CAAA,IAAAT,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAyCxE,MAAMW,GAAG,GAAG;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,oBAAoB,EAApBA,kCAAoB;EACpBC,UAAU,EAAVA,mBAAU;EACVC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAG/B;EACF,OAAOV,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<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,CAAAJ,CAAA,EAAAM,CAAA,EAAAG,CAAA,IAAAT,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAyCxE,MAAMW,GAAG,GAAG;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,oBAAoB,EAApBA,kCAAoB;EACpBC,UAAU,EAAVA,mBAAU;EACVC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAG/B;EACF,OAAOV,GAAG;AACZ","ignoreList":[]}
@@ -15,6 +15,120 @@ var _utils = require("./utils");
15
15
  * Loads and uses item(s) in an async collection.
16
16
  */
17
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)();
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
+
18
132
  /**
19
133
  * Resolves and stores at the given `path` of the global state elements of
20
134
  * an asynchronous data collection.
@@ -24,42 +138,12 @@ var _utils = require("./utils");
24
138
  // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
25
139
  // and reused in both hooks.
26
140
  function useAsyncCollection(idOrIds, path, loader, options = {}) {
27
- const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
141
+ const ids = normalizeIds(idOrIds);
28
142
  const maxage = options.maxage ?? _useAsyncData.DEFAULT_MAXAGE;
29
143
  const refreshAge = options.refreshAge ?? maxage;
30
144
  const garbageCollectAge = options.garbageCollectAge ?? maxage;
31
-
32
- // To avoid unnecessary work if consumer passes down the same IDs
33
- // in an unstable order.
34
- // TODO: Should we also filter out any duplicates? Or just assume consumer
35
- // knows what he is doing, and won't place duplicates into IDs array?e
36
- ids.sort();
37
145
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
38
- const {
39
- current: heap
40
- } = (0, _react.useRef)({});
41
- heap.globalState = globalState;
42
- heap.ids = ids;
43
- heap.path = path;
44
- heap.loader = loader;
45
- if (!heap.reload) {
46
- heap.reload = async customLoader => {
47
- const localLoader = customLoader || heap.loader;
48
- if (!localLoader || !heap.globalState || !heap.ids) {
49
- throw Error('Internal error');
50
- }
51
- for (let i = 0; i < heap.ids.length; ++i) {
52
- const id = heap.ids[i];
53
- const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;
54
-
55
- // eslint-disable-next-line no-await-in-loop
56
- await (0, _useAsyncData.load)(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap.globalState);
57
- }
58
- };
59
- }
60
- if (!Array.isArray(idOrIds)) {
61
- heap.reloadD = customLoader => heap.reload(customLoader && ((id, ...args) => customLoader(...args)));
62
- }
146
+ const heap = useHeap(ids, path, loader, globalState);
63
147
 
64
148
  // Server-side logic.
65
149
  if (globalState.ssrContext && !options.noSSR) {
@@ -82,51 +166,24 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
82
166
  } else {
83
167
  // Reference-counting & garbage collection.
84
168
 
169
+ const idsHash = (0, _utils.hash)(ids);
170
+
85
171
  // TODO: Violation of rules of hooks is fine here,
86
172
  // but perhaps it can be refactored to avoid the need for it.
87
173
  (0, _react.useEffect)(() => {
88
174
  // eslint-disable-line react-hooks/rules-of-hooks
89
- for (let i = 0; i < ids.length; ++i) {
90
- const id = ids[i];
91
- const itemPath = path ? `${path}.${id}` : `${id}`;
92
- const state = globalState.get(itemPath, {
93
- initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
94
- });
95
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
96
- globalState.set(numRefsPath, state.numRefs + 1);
97
- }
98
- return () => {
99
- for (let i = 0; i < ids.length; ++i) {
100
- const id = ids[i];
101
- const itemPath = path ? `${path}.${id}` : `${id}`;
102
- const state2 = globalState.get(itemPath);
103
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
104
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
105
- /* eslint-disable no-console */
106
- console.log(`ReactGlobalState - useAsyncCollection garbage collected at path ${itemPath || ''}`);
107
- /* eslint-enable no-console */
108
- }
109
- globalState.dropDependencies(itemPath || '');
110
- globalState.set(itemPath, {
111
- ...state2,
112
- data: null,
113
- numRefs: 0,
114
- timestamp: 0
115
- });
116
- } else {
117
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
118
- globalState.set(numRefsPath, state2.numRefs - 1);
119
- }
120
- }
121
- };
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.
122
180
  // eslint-disable-next-line react-hooks/exhaustive-deps
123
- }, [garbageCollectAge, globalState, path, ...ids]);
181
+ }, [garbageCollectAge, globalState, idsHash, path]);
124
182
 
125
183
  // NOTE: a bunch of Rules of Hooks ignored belows because in our very
126
184
  // special case the otherwise wrong behavior is actually what we need.
127
185
 
128
186
  // Data loading and refreshing.
129
- const loadTriggeredForIds = new Set();
130
187
  (0, _react.useEffect)(() => {
131
188
  // eslint-disable-line react-hooks/rules-of-hooks
132
189
  (async () => {
@@ -139,7 +196,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
139
196
  } = options;
140
197
  if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
141
198
  if (!deps) globalState.dropDependencies(itemPath);
142
- loadTriggeredForIds.add(id);
143
199
  // eslint-disable-next-line no-await-in-loop
144
200
  await (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
145
201
  data: state2.data,
@@ -149,26 +205,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
149
205
  }
150
206
  })();
151
207
  });
152
- (0, _react.useEffect)(() => {
153
- // eslint-disable-line react-hooks/rules-of-hooks
154
- (async () => {
155
- const {
156
- deps
157
- } = options;
158
- for (let i = 0; i < ids.length; ++i) {
159
- const id = ids[i];
160
- const itemPath = path ? `${path}.${id}` : `${id}`;
161
- if (deps && globalState.hasChangedDependencies(itemPath || '', deps) && !loadTriggeredForIds.has(id)) {
162
- // eslint-disable-next-line no-await-in-loop
163
- await (0, _useAsyncData.load)(itemPath, (oldData, meta) => loader(id, oldData, meta), globalState);
164
- }
165
- }
166
- })();
167
-
168
- // Here we need to default to empty array, so that this hook is re-evaluated
169
- // only when dependencies specified in options change, and it should not be
170
- // re-evaluated at all if no `deps` option is used.
171
- }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
172
208
  }
173
209
  const [localState] = (0, _useGlobalState.default)(path, {});
174
210
  if (!Array.isArray(idOrIds)) {
@@ -177,7 +213,7 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
177
213
  return {
178
214
  data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
179
215
  loading: !!e?.operationId,
180
- reload: heap.reloadD,
216
+ reload: heap.reloadSingle,
181
217
  timestamp
182
218
  };
183
219
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","useAsyncCollection","idOrIds","path","loader","options","ids","Array","isArray","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","sort","globalState","getGlobalState","current","heap","useRef","reload","customLoader","localLoader","Error","i","length","id","itemPath","load","oldData","meta","reloadD","args","ssrContext","noSSR","operationId","uuid","state","get","initialValue","newAsyncDataEnvelope","timestamp","pending","push","data","useEffect","numRefsPath","set","numRefs","state2","Date","now","process","env","NODE_ENV","isDebugMode","console","log","dropDependencies","loadTriggeredForIds","Set","deps","hasChangedDependencies","charAt","add","has","localState","useGlobalState","e","loading","res","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 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":";;;;;;;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;;AA2EA;AACA;AACA;AACA;;AAoDA;AACA;AACA;AACA,SAASO,kBAAkBA,CAIzBC,OAAoB,EACpBC,IAA+B,EAC/BC,MAA0C,EAC1CC,OAA6B,GAAG,CAAC,CAAC,EAC4B;EAC9D,MAAMC,GAAG,GAAGC,KAAK,CAACC,OAAO,CAACN,OAAO,CAAC,GAAGA,OAAO,GAAG,CAACA,OAAO,CAAC;EAExD,MAAMO,MAAc,GAAGJ,OAAO,CAACI,MAAM,IAAIC,4BAAc;EACvD,MAAMC,UAAkB,GAAGN,OAAO,CAACM,UAAU,IAAIF,MAAM;EACvD,MAAMG,iBAAyB,GAAGP,OAAO,CAACO,iBAAiB,IAAIH,MAAM;;EAErE;EACA;EACA;EACA;EACAH,GAAG,CAACO,IAAI,CAAC,CAAC;EAEV,MA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AAA,GAAAC,OAAA,CAAAC,OAAA,GAEc1E,kBAAkB","ignoreList":[]}
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","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","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>>();\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 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 // 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\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,GAAG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AE,KAAK;IACdtC,MAAM,EAAEH,IAAI,CAACG,MAAM;IACnBnB,SAAS,EAAE2D,MAAM,CAACC;EACpB,CAAC;EAED,KAAK,IAAIjF,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,MAAM6E,CAAC,GAAGF,UAAU,CAACzE,EAAE,CAAC;IACxB,MAAM4E,OAAO,GAAG,CAAC,CAACD,CAAC,EAAEjB,WAAW;IAChC,MAAMvC,SAAS,GAAGwD,CAAC,EAAExD,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACuE,KAAK,CAAC7E,EAAE,CAAC,GAAG;MACdgE,IAAI,EAAEb,MAAM,GAAGpC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAIwD,CAAC,EAAEX,IAAI,IAAI,IAAK;MAChEY,OAAO;MACPzD;IACF,CAAC;IACDb,GAAG,CAACsE,OAAO,KAAKA,OAAO;IACvB,IAAItE,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAA0E,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcjC,kBAAkB","ignoreList":[]}
@@ -45,13 +45,22 @@ function newAsyncDataEnvelope(initialData = null, {
45
45
  * @return Resolves once the operation is done.
46
46
  * @ignore
47
47
  */
48
- async function load(path, loader, globalState, old, operationId = `C${(0, _uuid.v4)()}`) {
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)()}`) {
49
54
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
50
55
  /* eslint-disable no-console */
51
56
  console.log(`ReactGlobalState: async data (re-)loading. Path: "${path || ''}"`);
52
57
  /* eslint-enable no-console */
53
58
  }
54
59
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
60
+ {
61
+ const prevOperationId = globalState.get(operationIdPath);
62
+ if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);
63
+ }
55
64
  globalState.set(operationIdPath, operationId);
56
65
  let definedOld = old;
57
66
  if (!definedOld) {
@@ -68,9 +77,24 @@ async function load(path, loader, globalState, old, operationId = `C${(0, _uuid.
68
77
  const opid = globalState.get(path).operationId;
69
78
  return opid !== operationId;
70
79
  },
71
- oldDataTimestamp: definedOld.timestamp
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
+ }
72
88
  });
73
- const data = dataOrPromise instanceof Promise ? await dataOrPromise : dataOrPromise;
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
+ }
74
98
  const state = globalState.get(path);
75
99
  if (operationId === state.operationId) {
76
100
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
@@ -167,7 +191,6 @@ function useAsyncData(path, loader, options = {}) {
167
191
  // special case the otherwise wrong behavior is actually what we need.
168
192
 
169
193
  // Data loading and refreshing.
170
- let loadTriggered = false;
171
194
  (0, _react.useEffect)(() => {
172
195
  // eslint-disable-line react-hooks/rules-of-hooks
173
196
  const state2 = globalState.get(path);
@@ -181,7 +204,6 @@ function useAsyncData(path, loader, options = {}) {
181
204
 
182
205
  // Data at the path are stale, and are not being loaded.
183
206
  || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
184
- loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
185
207
  if (!deps) globalState.dropDependencies(path || '');
186
208
  load(path, loader, globalState, {
187
209
  data: state2.data,
@@ -189,19 +211,6 @@ function useAsyncData(path, loader, options = {}) {
189
211
  });
190
212
  }
191
213
  });
192
- (0, _react.useEffect)(() => {
193
- // eslint-disable-line react-hooks/rules-of-hooks
194
- const {
195
- deps
196
- } = options;
197
- if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
198
- load(path, loader, globalState);
199
- }
200
-
201
- // Here we need to default to empty array, so that this hook is re-evaluated
202
- // only when dependencies specified in options change, and it should not be
203
- // re-evaluated at all if no `deps` option is used.
204
- }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
205
214
  }
206
215
  const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
207
216
  return {