@dr.pogodin/react-global-state 0.17.0 → 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.
- package/build/common/GlobalState.js +32 -0
- package/build/common/GlobalState.js.map +1 -1
- package/build/common/useAsyncCollection.js +0 -22
- package/build/common/useAsyncCollection.js.map +1 -1
- package/build/common/useAsyncData.js +27 -18
- package/build/common/useAsyncData.js.map +1 -1
- package/build/module/GlobalState.js +34 -0
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/useAsyncCollection.js +0 -22
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js +21 -17
- package/build/module/useAsyncData.js.map +1 -1
- package/build/types/GlobalState.d.ts +21 -0
- package/build/types/useAsyncCollection.d.ts +1 -0
- package/build/types/useAsyncData.d.ts +1 -0
- package/package.json +9 -9
- package/src/GlobalState.ts +33 -0
- package/src/useAsyncCollection.ts +1 -28
- package/src/useAsyncData.ts +28 -19
|
@@ -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,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;MAC1D;MACA,IAAIC,GAAG,GAAG,8BAA8B;MACxC,IAAIR,UAAU,EAAEQ,GAAG,IAAI,aAAa;MACpCC,OAAO,CAACC,cAAc,CAACF,GAAG,CAAC;MAC3BC,OAAO,CAACE,GAAG,CAAC,gBAAgB,EAAE,IAAAC,sBAAe,EAACjB,YAAY,CAAC,CAAC;MAC5Dc,OAAO,C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AEA;AACF;AACA;AACA;AACA;AACA;AACA;EACEkB,OAAOA,CAACC,QAAmB,EAAE;IAC3B,IAAI,IAAI,CAACnD,UAAU,EAAE,MAAM,IAAIoD,KAAK,CAAC5D,gBAAgB,CAAC;IAEtD,MAAMI,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,MAAM6C,GAAG,GAAG7C,QAAQ,CAACyD,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIV,GAAG,IAAI,CAAC,EAAE;MACZ7C,QAAQ,CAAC6C,GAAG,CAAC,GAAG7C,QAAQ,CAACA,QAAQ,CAACwB,MAAM,GAAG,CAAC,CAAE;MAC9CxB,QAAQ,CAAC0D,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAACnD,UAAU,EAAE,MAAM,IAAIoD,KAAK,CAAC5D,gBAAgB,CAAC;IAEtD,MAAMI,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,IAAIA,QAAQ,CAACyD,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCvD,QAAQ,CAAC4D,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF;AAACM,OAAA,CAAAC,OAAA,GAAAjE,WAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GlobalState.js","names":["_lodash","require","_utils","ERR_NO_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,uBAAuB,GAA+B,CAAC,CAAC;EAEzD,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,CA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D,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":[]}
|
|
@@ -184,7 +184,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
184
184
|
// special case the otherwise wrong behavior is actually what we need.
|
|
185
185
|
|
|
186
186
|
// Data loading and refreshing.
|
|
187
|
-
const loadTriggeredForIds = new Set();
|
|
188
187
|
(0, _react.useEffect)(() => {
|
|
189
188
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
190
189
|
(async () => {
|
|
@@ -197,7 +196,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
197
196
|
} = options;
|
|
198
197
|
if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
|
|
199
198
|
if (!deps) globalState.dropDependencies(itemPath);
|
|
200
|
-
loadTriggeredForIds.add(id);
|
|
201
199
|
// eslint-disable-next-line no-await-in-loop
|
|
202
200
|
await (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
|
|
203
201
|
data: state2.data,
|
|
@@ -207,26 +205,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
207
205
|
}
|
|
208
206
|
})();
|
|
209
207
|
});
|
|
210
|
-
(0, _react.useEffect)(() => {
|
|
211
|
-
// eslint-disable-line react-hooks/rules-of-hooks
|
|
212
|
-
(async () => {
|
|
213
|
-
const {
|
|
214
|
-
deps
|
|
215
|
-
} = options;
|
|
216
|
-
for (let i = 0; i < ids.length; ++i) {
|
|
217
|
-
const id = ids[i];
|
|
218
|
-
const itemPath = path ? `${path}.${id}` : `${id}`;
|
|
219
|
-
if (deps && globalState.hasChangedDependencies(itemPath || '', deps) && !loadTriggeredForIds.has(id)) {
|
|
220
|
-
// eslint-disable-next-line no-await-in-loop
|
|
221
|
-
await (0, _useAsyncData.load)(itemPath, (oldData, meta) => loader(id, oldData, meta), globalState);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
})();
|
|
225
|
-
|
|
226
|
-
// Here we need to default to empty array, so that this hook is re-evaluated
|
|
227
|
-
// only when dependencies specified in options change, and it should not be
|
|
228
|
-
// re-evaluated at all if no `deps` option is used.
|
|
229
|
-
}, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
|
|
230
208
|
}
|
|
231
209
|
const [localState] = (0, _useGlobalState.default)(path, {});
|
|
232
210
|
if (!Array.isArray(idOrIds)) {
|
|
@@ -1 +1 @@
|
|
|
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","loadTriggeredForIds","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 }) => 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":";;;;;;;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;A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AACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,MAAM8E,CAAC,GAAGF,UAAU,CAAC1E,EAAE,CAAC;IACxB,MAAM6E,OAAO,GAAG,CAAC,CAACD,CAAC,EAAElB,WAAW;IAChC,MAAMvC,SAAS,GAAGyD,CAAC,EAAEzD,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACwE,KAAK,CAAC9E,EAAE,CAAC,GAAG;MACdgE,IAAI,EAAEb,MAAM,GAAGpC,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAIyD,CAAC,EAAEZ,IAAI,IAAI,IAAK;MAChEa,OAAO;MACP1D;IACF,CAAC;IACDb,GAAG,CAACuE,OAAO,KAAKA,OAAO;IACvB,IAAIvE,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAA2E,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,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,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,IAAII,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,IAAIG,QAAQ,GAAGL,UAAU,CAACI,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAAQ;MAAEC,OAAO,EAAE,CAAC,GAAGD,QAAQ,CAACC;IAAQ,CAAC,CAAC,KACnED,QAAQ,GAAG,IAAAE,kCAAoB,EAAU,IAAI,EAAE;MAAED,OAAO,EAAE;IAAE,CAAC,CAAC;IACnEN,UAAU,CAACI,EAAE,CAAC,GAAGC,QAAQ;EAC3B;EAEAN,EAAE,CAACS,GAAG,CAA2BV,IAAI,EAAEE,UAAU,CAAC;AACpD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,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,
|
|
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
|
-
|
|
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 {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","set","definedOld","e","get","dataOrPromise","isAborted","opid","oldDataTimestamp","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","loadTriggered","deps","hasChangedDependencies","charAt","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n });\n\n const data: DataT | null = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (\n deps\n && globalState.hasChangedDependencies(path || '', deps)\n && !loadTriggered\n ) {\n load(path, loader, globalState);\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<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;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I,CAACE,MAAM;IACnBzC,SAAS,EAAEyD,UAAU,CAACzD;EACxB,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","prevOperationId","get","asyncDataLoadDone","set","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","charAt","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n let data: DataT | null;\n\n try {\n data = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\n } finally {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n }\n\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path || '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAqBnC,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;A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6,6 +6,7 @@ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.h
|
|
|
6
6
|
import { get, isFunction, isObject, isNil, set, toPath } from 'lodash';
|
|
7
7
|
import { cloneDeepForLog, isDebugMode } from "./utils";
|
|
8
8
|
const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
|
|
9
|
+
var _asyncDataAbortCallbacks = /*#__PURE__*/new WeakMap();
|
|
9
10
|
var _dependencies = /*#__PURE__*/new WeakMap();
|
|
10
11
|
var _initialState = /*#__PURE__*/new WeakMap();
|
|
11
12
|
var _watchers = /*#__PURE__*/new WeakMap();
|
|
@@ -18,6 +19,7 @@ export default class GlobalState {
|
|
|
18
19
|
* @param ssrContext Server-side rendering context.
|
|
19
20
|
*/
|
|
20
21
|
constructor(initialState, ssrContext) {
|
|
22
|
+
_classPrivateFieldInitSpec(this, _asyncDataAbortCallbacks, {});
|
|
21
23
|
_classPrivateFieldInitSpec(this, _dependencies, {});
|
|
22
24
|
_classPrivateFieldInitSpec(this, _initialState, void 0);
|
|
23
25
|
// TODO: It is tempting to replace watchers here by
|
|
@@ -49,6 +51,25 @@ export default class GlobalState {
|
|
|
49
51
|
}
|
|
50
52
|
}
|
|
51
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Returns the number of currently registered async data abort callbacks,
|
|
56
|
+
* just for the sake of testing the library.
|
|
57
|
+
*/
|
|
58
|
+
get numAsyncDataAbortCallbacks() {
|
|
59
|
+
return Object.keys(_classPrivateFieldGet(_asyncDataAbortCallbacks, this)).length;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* If `aborted` is "true" and there is an abort callback registered for
|
|
64
|
+
* the specified operation, it triggers the callback. Then, in any case,
|
|
65
|
+
* it drops the callback.
|
|
66
|
+
*/
|
|
67
|
+
asyncDataLoadDone(opid, aborted) {
|
|
68
|
+
var _classPrivateFieldGet2, _classPrivateFieldGet3;
|
|
69
|
+
if (aborted) (_classPrivateFieldGet2 = (_classPrivateFieldGet3 = _classPrivateFieldGet(_asyncDataAbortCallbacks, this))[opid]) === null || _classPrivateFieldGet2 === void 0 || _classPrivateFieldGet2.call(_classPrivateFieldGet3);
|
|
70
|
+
delete _classPrivateFieldGet(_asyncDataAbortCallbacks, this)[opid];
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
/**
|
|
53
74
|
* Drops the record of dependencies, if any, for the given path.
|
|
54
75
|
*/
|
|
@@ -61,6 +82,11 @@ export default class GlobalState {
|
|
|
61
82
|
* the given `path`. If they are, `deps` are recorded as the new deps for
|
|
62
83
|
* the `path`, and also the array is frozen, to prevent it from being
|
|
63
84
|
* modified.
|
|
85
|
+
*
|
|
86
|
+
* TODO: This may not work as expected if path string is not normalized,
|
|
87
|
+
* and the for the same path different alternative ways to spell it down
|
|
88
|
+
* are used. We should normalize given path here, I guess, or on a higher
|
|
89
|
+
* level in the logic?
|
|
64
90
|
*/
|
|
65
91
|
hasChangedDependencies(path, deps) {
|
|
66
92
|
const prevDeps = _classPrivateFieldGet(_dependencies, this)[path];
|
|
@@ -113,6 +139,14 @@ export default class GlobalState {
|
|
|
113
139
|
}
|
|
114
140
|
}
|
|
115
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Registers an abort callback for an async data retrieval operation with
|
|
144
|
+
* the given operation ID. Throws if already registered.
|
|
145
|
+
*/
|
|
146
|
+
setAsyncDataAbortCallback(opid, cb) {
|
|
147
|
+
_classPrivateFieldGet(_asyncDataAbortCallbacks, this)[opid] = cb;
|
|
148
|
+
}
|
|
149
|
+
|
|
116
150
|
/**
|
|
117
151
|
* Sets entire state, the same way as .set(null, value) would do.
|
|
118
152
|
* @param value
|