@dr.pogodin/react-global-state 0.14.1 → 0.14.2
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.map +1 -1
- package/build/common/index.js +23 -14
- package/build/common/index.js.map +1 -1
- package/build/common/useAsyncCollection.js +2 -3
- package/build/common/useAsyncCollection.js.map +1 -1
- package/build/common/useAsyncData.js +17 -4
- package/build/common/useAsyncData.js.map +1 -1
- package/build/common/useGlobalState.js.map +1 -1
- package/build/module/GlobalState.js +2 -2
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/index.js +3 -2
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js +1 -1
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js +18 -4
- package/build/module/useAsyncData.js.map +1 -1
- package/build/module/useGlobalState.js.map +1 -1
- package/build/types/index.d.ts +3 -3
- package/build/types/useAsyncData.d.ts +3 -2
- package/package.json +20 -22
- package/src/index.ts +3 -9
- package/src/useAsyncCollection.ts +2 -1
- package/src/useAsyncData.ts +34 -12
- package/tsconfig.json +1 -1
- package/tstyche.config.json +6 -0
|
@@ -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","cloneDeep","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 cloneDeep,\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 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:', cloneDeep(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:', cloneDeep(value));\n console.log('New state:', cloneDeep(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,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MACZ7C,QAAQ,CAAC6C,GAAG,CAAC,GAAG7C,QAAQ,CAACA,QAAQ,CAACwB,MAAM,GAAG,CAAC,CAAC;MAC7CxB,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","dependencies","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeep","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 cloneDeep,\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 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:', cloneDeep(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:', cloneDeep(value));\n console.log('New state:', cloneDeep(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;AAYA,IAAAC,MAAA,GAAAD,OAAA;AAUA,MAAME,gBAAgB,GAAG,gDAAgD;AAO1D,MAAMC,WAAW,CAG9B;EAGA,CAACC,YAAY,GAAuC,CAAC,CAAC;EAEtD,CAACC,YAAY;;EAEb;EACA;EACA;EACA;EACA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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":[]}
|
package/build/common/index.js
CHANGED
|
@@ -4,6 +4,16 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
|
|
|
4
4
|
Object.defineProperty(exports, "__esModule", {
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
|
+
var _exportNames = {
|
|
8
|
+
withGlobalStateType: true,
|
|
9
|
+
GlobalState: true,
|
|
10
|
+
GlobalStateProvider: true,
|
|
11
|
+
getGlobalState: true,
|
|
12
|
+
getSsrContext: true,
|
|
13
|
+
SsrContext: true,
|
|
14
|
+
useAsyncCollection: true,
|
|
15
|
+
useGlobalState: true
|
|
16
|
+
};
|
|
7
17
|
Object.defineProperty(exports, "GlobalState", {
|
|
8
18
|
enumerable: true,
|
|
9
19
|
get: function () {
|
|
@@ -34,24 +44,12 @@ Object.defineProperty(exports, "getSsrContext", {
|
|
|
34
44
|
return _GlobalStateProvider.getSsrContext;
|
|
35
45
|
}
|
|
36
46
|
});
|
|
37
|
-
Object.defineProperty(exports, "newAsyncDataEnvelope", {
|
|
38
|
-
enumerable: true,
|
|
39
|
-
get: function () {
|
|
40
|
-
return _useAsyncData.newAsyncDataEnvelope;
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
47
|
Object.defineProperty(exports, "useAsyncCollection", {
|
|
44
48
|
enumerable: true,
|
|
45
49
|
get: function () {
|
|
46
50
|
return _useAsyncCollection.default;
|
|
47
51
|
}
|
|
48
52
|
});
|
|
49
|
-
Object.defineProperty(exports, "useAsyncData", {
|
|
50
|
-
enumerable: true,
|
|
51
|
-
get: function () {
|
|
52
|
-
return _useAsyncData.default;
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
53
|
Object.defineProperty(exports, "useGlobalState", {
|
|
56
54
|
enumerable: true,
|
|
57
55
|
get: function () {
|
|
@@ -63,7 +61,18 @@ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
|
|
|
63
61
|
var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
|
|
64
62
|
var _SsrContext = _interopRequireDefault(require("./SsrContext"));
|
|
65
63
|
var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
|
|
66
|
-
var _useAsyncData =
|
|
64
|
+
var _useAsyncData = require("./useAsyncData");
|
|
65
|
+
Object.keys(_useAsyncData).forEach(function (key) {
|
|
66
|
+
if (key === "default" || key === "__esModule") return;
|
|
67
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
68
|
+
if (key in exports && exports[key] === _useAsyncData[key]) return;
|
|
69
|
+
Object.defineProperty(exports, key, {
|
|
70
|
+
enumerable: true,
|
|
71
|
+
get: function () {
|
|
72
|
+
return _useAsyncData[key];
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
});
|
|
67
76
|
var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
|
|
68
77
|
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
|
69
78
|
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
|
@@ -75,7 +84,7 @@ const api = {
|
|
|
75
84
|
newAsyncDataEnvelope: _useAsyncData.newAsyncDataEnvelope,
|
|
76
85
|
SsrContext: _SsrContext.default,
|
|
77
86
|
useAsyncCollection: _useAsyncCollection.default,
|
|
78
|
-
useAsyncData: _useAsyncData.
|
|
87
|
+
useAsyncData: _useAsyncData.useAsyncData,
|
|
79
88
|
useGlobalState: _useGlobalState.default
|
|
80
89
|
};
|
|
81
90
|
function withGlobalStateType() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n} from './useAsyncCollection';\n\nimport {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport * from './useAsyncData';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n useAsyncCollection,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAIA,IAAAK,aAAA,GAAAL,OAAA;AAUAM,MAAA,CAAAC,IAAA,CAAAF,aAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,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AX,CAAA,CAAAW,CAAA,YAAAJ,CAAA,CAAAF,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAU,GAAA,CAAAb,CAAA,EAAAO,CAAA,GAAAA,CAAA;AAmCxE,MAAMO,GAAG,GAAG;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,oBAAoB,EAApBA,kCAAoB;EACpBC,UAAU,EAAVA,mBAAU;EACVC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAG/B;EACF,OAAOV,GAAG;AACZ","ignoreList":[]}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.default = void 0;
|
|
8
|
-
var _useAsyncData =
|
|
7
|
+
var _useAsyncData = require("./useAsyncData");
|
|
9
8
|
/**
|
|
10
9
|
* Loads and uses an item in an async collection.
|
|
11
10
|
*/
|
|
@@ -55,7 +54,7 @@ var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
|
|
|
55
54
|
|
|
56
55
|
function useAsyncCollection(id, path, loader, options = {}) {
|
|
57
56
|
const itemPath = path ? `${path}.${id}` : id;
|
|
58
|
-
return (0, _useAsyncData.
|
|
57
|
+
return (0, _useAsyncData.useAsyncData)(itemPath, oldData => loader(id, oldData), options);
|
|
59
58
|
}
|
|
60
59
|
var _default = exports.default = useAsyncCollection;
|
|
61
60
|
//# sourceMappingURL=useAsyncCollection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","require","useAsyncCollection","id","path","loader","options","itemPath","useAsyncData","oldData","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n useAsyncData,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends 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>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;AAIA,IAAAA,aAAA,GAAAC,OAAA;AAJA;AACA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;EACzB,MAAMC,QAAQ,GAAGH,IAAI,GAAG,GAAGA,IAAI,IAAID,EAAE,EAAE,GAAGA,EAAE;EAC5C,OAAO,IAAAK,0BAAY,EACjBD,QAAQ,EACPE,OAAqB,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAC9CH,OACF,CAAC;AACH;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,kBAAkB","ignoreList":[]}
|
|
@@ -4,8 +4,8 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
|
|
|
4
4
|
Object.defineProperty(exports, "__esModule", {
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
|
-
exports.default = void 0;
|
|
8
7
|
exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
|
|
8
|
+
exports.useAsyncData = useAsyncData;
|
|
9
9
|
var _lodash = require("lodash");
|
|
10
10
|
var _react = require("react");
|
|
11
11
|
var _uuid = require("uuid");
|
|
@@ -53,7 +53,8 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
|
|
|
53
53
|
const operationId = opIdPrefix + (0, _uuid.v4)();
|
|
54
54
|
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
55
55
|
globalState.set(operationIdPath, operationId);
|
|
56
|
-
const
|
|
56
|
+
const dataOrLoader = loader(oldData || globalState.get(path).data);
|
|
57
|
+
const data = dataOrLoader instanceof Promise ? await dataOrLoader : dataOrLoader;
|
|
57
58
|
const state = globalState.get(path);
|
|
58
59
|
if (operationId === state.operationId) {
|
|
59
60
|
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
@@ -135,6 +136,19 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
135
136
|
const state = globalState.get(path, {
|
|
136
137
|
initialValue: newAsyncDataEnvelope()
|
|
137
138
|
});
|
|
139
|
+
const {
|
|
140
|
+
current: heap
|
|
141
|
+
} = (0, _react.useRef)({});
|
|
142
|
+
heap.globalState = globalState;
|
|
143
|
+
heap.path = path;
|
|
144
|
+
heap.loader = loader;
|
|
145
|
+
if (!heap.reload) {
|
|
146
|
+
heap.reload = customLoader => {
|
|
147
|
+
const localLoader = customLoader || heap.loader;
|
|
148
|
+
if (!localLoader || !heap.globalState) throw Error('Internal error');
|
|
149
|
+
return load(heap.path, localLoader, heap.globalState, null);
|
|
150
|
+
};
|
|
151
|
+
}
|
|
138
152
|
if (globalState.ssrContext && !options.noSSR) {
|
|
139
153
|
if (!state.timestamp && !state.operationId) {
|
|
140
154
|
globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
|
|
@@ -204,9 +218,8 @@ function useAsyncData(path, loader, options = {}) {
|
|
|
204
218
|
return {
|
|
205
219
|
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
206
220
|
loading: Boolean(localState.operationId),
|
|
207
|
-
reload:
|
|
221
|
+
reload: heap.reload,
|
|
208
222
|
timestamp: localState.timestamp
|
|
209
223
|
};
|
|
210
224
|
}
|
|
211
|
-
var _default = exports.default = useAsyncData;
|
|
212
225
|
//# sourceMappingURL=useAsyncData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","get","state","groupCollapsed","cloneDeep","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","useGlobalState","loading","Boolean","reload","customLoader","_default","exports","default"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } 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 isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\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: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\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 */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\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: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\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. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\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 === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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 if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\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 if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\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\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default 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,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,QAAA,GAAAH,OAAA;AAEA,IAAAI,oBAAA,GAAAJ,OAAA;AACA,IAAAK,eAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAbA;AACA;AACA;;AAsBA,MAAMQ,cAAc,GAAG,CAAC,GAAGC,eAAM,CAAC,CAAC;;AAY5B,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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeG,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EACrBC,UAAqB,GAAG,GAAG,EACZ;EACf,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW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IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEiC,MAAM,CAACtC,IAAI,CAAC;QAC5CwC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;IAEF,IAAAJ,gBAAS,EAAC,MAAM;MAAE;MAChB,MAAM;QAAEM;MAAK,CAAC,GAAGjB,OAAO;MACxB,IAAIiB,IAAI,IAAIrC,WAAW,CAACsC,sBAAsB,CAACxC,IAAI,IAAI,EAAE,EAAEuC,IAAI,CAAC,IAAI,CAACF,aAAa,EAAE;QAClFtC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEoB,OAAO,CAACiB,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjC1C,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE0B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGsB,UAAU,CAAC7C,SAAS,GAAG,IAAI,GAAG6C,UAAU,CAAC5C,IAAI;IACzE8C,OAAO,EAAEC,OAAO,CAACH,UAAU,CAAC3C,WAAW,CAAC;IAExC+C,MAAM,EAAGC,YAAsC,IAAK/C,IAAI,CACtDC,IAAI,EACJ8C,YAAY,IAAI7C,MAAM,EACtBC,WAAW,EACX,IACF,CAAC;IAEDN,SAAS,EAAE6C,UAAU,CAAC7C;EACxB,CAAC;AACH;AAAC,IAAAmD,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc5B,YAAY","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","dataOrLoader","get","Promise","state","groupCollapsed","cloneDeep","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\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 isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\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 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 */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n const dataOrLoader = loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n\n const data: DataT = dataOrLoader instanceof Promise\n ? await dataOrLoader : dataOrLoader;\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: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\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. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\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 === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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, null);\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, state.data, 'S'),\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 if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\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,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,QAAA,GAAAH,OAAA;AAEA,IAAAI,oBAAA,GAAAJ,OAAA;AACA,IAAAK,eAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAbA;AACA;AACA;;AAsBA,MAAMQ,cAAc,GAAG,CAAC,GAAGC,eAAM,CAAC,CAAC;;AAe5B,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,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AS,EAAC,MAAM;MAAE;MAChB,MAAM;QAAEM;MAAK,CAAC,GAAGxB,OAAO;MACxB,IAAIwB,IAAI,IAAI9C,WAAW,CAAC+C,sBAAsB,CAACjD,IAAI,IAAI,EAAE,EAAEgD,IAAI,CAAC,IAAI,CAACF,aAAa,EAAE;QAClF/C,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEsB,OAAO,CAACwB,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCnD,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE4B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG6B,UAAU,CAACtD,SAAS,GAAG,IAAI,GAAGsD,UAAU,CAACrD,IAAI;IACzEuD,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACpD,WAAW,CAAC;IACxCoC,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBtC,SAAS,EAAEsD,UAAU,CAACtD;EACxB,CAAC;AACH","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAoCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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ACG,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC9B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACM,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcvC,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAoCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AASA,SAASK,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAiB,CAAC;EAEpC,IAAIC,EAAkB;EACtB,IAAI,CAACF,GAAG,CAACG,OAAO,EAAE;IAChB,MAAMC,OAAO,GAAG,IAAIC,gBAAO,CAAC,CAAC;IAC7BL,GAAG,CAACG,OAAO,GAAG;MACZC,OAAO;MACPN,WAAW;MACXF,IAAI;MACJU,MAAM,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,WAAW;EAC5BI,EAAE,CAACN,IAAI,GAAGA,IAAI;EAEdM,EAAE,CAACmB,KAAK,GAAG,IAAAM,2BAAoB,EAC7BzB,EAAE,CAACqB,SAAS,EACZ,MAAMrB,EAAE,CAAEJ,WAAW,CAACY,GAAG,CAAkBR,EAAE,CAAEN,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMK,EAAE,CAAEJ,WAAW,CAACY,GAAG,CACvBR,EAAE,CAAEN,IAAI,EACR;IAAEC,YAAY;IAAE+B,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAED,IAAAC,gBAAS,EAAC,MAAM;IACd,MAAM;MAAEH;IAAQ,CAAC,GAAG1B,GAAG,CAACG,OAAQ;IAChCL,WAAW,CAACgC,KAAK,CAACJ,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM5B,WAAW,CAACiC,OAAO,CAACL,OAAO,CAAC;EAC3C,CAAC,EAAE,CAAC5B,WAAW,CAAC,CAAC;EAEjB,IAAA+B,gBAAS,EAAC,MAAM;IACd7B,GAAG,CAACG,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC9B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACM,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcvC,cAAc","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
function _classPrivateFieldInitSpec(
|
|
2
|
-
function _checkPrivateRedeclaration(
|
|
1
|
+
function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
|
|
2
|
+
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
|
|
3
3
|
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
|
|
4
4
|
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
|
|
5
5
|
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GlobalState.js","names":["cloneDeep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\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 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:', cloneDeep(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:', cloneDeep(value));\n console.log('New state:', cloneDeep(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,SACEA,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAOEC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,aAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,SAAA,oBAAAF,OAAA;AAAA,IAAAG,eAAA,oBAAAH,OAAA;AAAA,IAAAI,aAAA,oBAAAJ,OAAA;AAO1E,eAAe,MAAMK,WAAW,CAG9B;EAiBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAAAC,0BAAA,OAAAV,aAAA,EAtBkD,CAAC,CAAC;IAAAU,0BAAA,OAAAR,aAAA;IAItD;IACA;IACA;IACA;IAAAQ,0B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CAACF,QAAQ,CAAC;IACtC,IAAIR,GAAG,IAAI,CAAC,EAAE;MACZJ,QAAQ,CAACI,GAAG,CAAC,GAAGJ,QAAQ,CAACA,QAAQ,CAACd,MAAM,GAAG,CAAC,CAAC;MAC7Cc,QAAQ,CAACe,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC/C,UAAU,EAAE,MAAM,IAAIgD,KAAK,CAAC1D,gBAAgB,CAAC;IAEtD,MAAM6C,QAAQ,GAAA7B,qBAAA,CAAAZ,SAAA,EAAG,IAAI,CAAU;IAC/B,IAAIyC,QAAQ,CAACc,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCZ,QAAQ,CAACiB,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GlobalState.js","names":["cloneDeep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\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 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:', cloneDeep(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:', cloneDeep(value));\n console.log('New state:', cloneDeep(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,SACEA,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAOEC,WAAW;AAGb,MAA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
|
|
2
2
|
import GlobalStateProvider, { getGlobalState, getSsrContext } from "./GlobalStateProvider";
|
|
3
3
|
import SsrContext from "./SsrContext";
|
|
4
4
|
import useAsyncCollection from "./useAsyncCollection";
|
|
5
|
-
import
|
|
5
|
+
import { newAsyncDataEnvelope, useAsyncData } from "./useAsyncData";
|
|
6
6
|
import useGlobalState from "./useGlobalState";
|
|
7
|
-
export
|
|
7
|
+
export * from "./useAsyncData";
|
|
8
|
+
export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, SsrContext, useAsyncCollection, useGlobalState };
|
|
8
9
|
const api = {
|
|
9
10
|
getGlobalState,
|
|
10
11
|
getSsrContext,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","
|
|
1
|
+
{"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n} from './useAsyncCollection';\n\nimport {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport * from './useAsyncData';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n useAsyncCollection,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAIzB,SAEEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAIrB;AAMA,SACEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBG,UAAU,EACVC,kBAAkB,EAClBG,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBK,oBAAoB;EACpBF,UAAU;EACVC,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n useAsyncData,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends 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>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAIEA,YAAY;;AAQd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAG,GAAGA,IAAI,IAAID,EAAE,EAAE,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB","ignoreList":[]}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { cloneDeep } from 'lodash';
|
|
6
|
-
import { useEffect } from 'react';
|
|
6
|
+
import { useEffect, useRef } from 'react';
|
|
7
7
|
import { v4 as uuid } from 'uuid';
|
|
8
8
|
import { MIN_MS } from '@dr.pogodin/js-utils';
|
|
9
9
|
import { getGlobalState } from "./GlobalStateProvider";
|
|
@@ -48,7 +48,8 @@ async function load(path, loader, globalState, oldData) {
|
|
|
48
48
|
const operationId = opIdPrefix + uuid();
|
|
49
49
|
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
50
50
|
globalState.set(operationIdPath, operationId);
|
|
51
|
-
const
|
|
51
|
+
const dataOrLoader = loader(oldData || globalState.get(path).data);
|
|
52
|
+
const data = dataOrLoader instanceof Promise ? await dataOrLoader : dataOrLoader;
|
|
52
53
|
const state = globalState.get(path);
|
|
53
54
|
if (operationId === state.operationId) {
|
|
54
55
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
@@ -131,6 +132,19 @@ function useAsyncData(path, loader) {
|
|
|
131
132
|
const state = globalState.get(path, {
|
|
132
133
|
initialValue: newAsyncDataEnvelope()
|
|
133
134
|
});
|
|
135
|
+
const {
|
|
136
|
+
current: heap
|
|
137
|
+
} = useRef({});
|
|
138
|
+
heap.globalState = globalState;
|
|
139
|
+
heap.path = path;
|
|
140
|
+
heap.loader = loader;
|
|
141
|
+
if (!heap.reload) {
|
|
142
|
+
heap.reload = customLoader => {
|
|
143
|
+
const localLoader = customLoader || heap.loader;
|
|
144
|
+
if (!localLoader || !heap.globalState) throw Error('Internal error');
|
|
145
|
+
return load(heap.path, localLoader, heap.globalState, null);
|
|
146
|
+
};
|
|
147
|
+
}
|
|
134
148
|
if (globalState.ssrContext && !options.noSSR) {
|
|
135
149
|
if (!state.timestamp && !state.operationId) {
|
|
136
150
|
globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
|
|
@@ -200,9 +214,9 @@ function useAsyncData(path, loader) {
|
|
|
200
214
|
return {
|
|
201
215
|
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
202
216
|
loading: Boolean(localState.operationId),
|
|
203
|
-
reload:
|
|
217
|
+
reload: heap.reload,
|
|
204
218
|
timestamp: localState.timestamp
|
|
205
219
|
};
|
|
206
220
|
}
|
|
207
|
-
export
|
|
221
|
+
export { useAsyncData };
|
|
208
222
|
//# sourceMappingURL=useAsyncData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","loading","Boolean","reload","customLoader"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } 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 isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\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: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\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 */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\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: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\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. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\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 === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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 if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\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 if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\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\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default 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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,GAAAJ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeG,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EAEN;EAAA,IADfC,UAAqB,GAAAZ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,GAAG;EAE3B,IAAIa,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAInB,WA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AC,CAAC,KAAK,GAAG,CAAC,EAAE;QAChEjC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE2B,MAAM,CAAChC,IAAI,CAAC;QAC5CkC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;IAEFjD,SAAS,CAAC,MAAM;MAAE;MAChB,MAAM;QAAEmD;MAAK,CAAC,GAAGd,OAAO;MACxB,IAAIc,IAAI,IAAI/B,WAAW,CAACgC,sBAAsB,CAAClC,IAAI,IAAI,EAAE,EAAEiC,IAAI,CAAC,IAAI,CAACF,aAAa,EAAE;QAClFhC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEiB,OAAO,CAACc,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAGhD,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEuB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGmB,UAAU,CAACvC,SAAS,GAAG,IAAI,GAAGuC,UAAU,CAACtC,IAAI;IACzEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACrC,WAAW,CAAC;IAExCwC,MAAM,EAAGC,YAAsC,IAAKxC,IAAI,CACtDC,IAAI,EACJuC,YAAY,IAAItC,MAAM,EACtBC,WAAW,EACX,IACF,CAAC;IAEDN,SAAS,EAAEuC,UAAU,CAACvC;EACxB,CAAC;AACH;AAEA,eAAesB,YAAY","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","dataOrLoader","get","Promise","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\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 isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\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 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 */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n const dataOrLoader = loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n\n const data: DataT = dataOrLoader instanceof Promise\n ? await dataOrLoader : dataOrLoader;\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: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\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. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\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 === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\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, null);\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, state.data, 'S'),\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 if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAenC,OAAO,SAASK,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,G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AAEC,MAAM,EAAEC,WAAW,EAAEmC,MAAM,CAACxC,IAAI,CAAC;QAC5C0C,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;IAEF1D,SAAS,CAAC,MAAM;MAAE;MAChB,MAAM;QAAE4D;MAAK,CAAC,GAAGpB,OAAO;MACxB,IAAIoB,IAAI,IAAIvC,WAAW,CAACwC,sBAAsB,CAAC1C,IAAI,IAAI,EAAE,EAAEyC,IAAI,CAAC,IAAI,CAACF,aAAa,EAAE;QAClFxC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEmB,OAAO,CAACoB,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAGxD,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGyB,UAAU,CAAC/C,SAAS,GAAG,IAAI,GAAG+C,UAAU,CAAC9C,IAAI;IACzE+C,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC7C,WAAW,CAAC;IACxC8B,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBhC,SAAS,EAAE+C,UAAU,CAAC/C;EACxB,CAAC;AACH;AAEA,SAASwB,YAAY","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,OAAO,QAAQ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,CAAC;EAEjBT,SAAS,CAAC,MAAM;IACdU,GAAG,CAACE,OAAO,CAAEmB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACxB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACI,EAAE,CAACe,KAAK,EAAEf,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","get","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,OAAO,QAAQ,sBAAsB;AAG9C,SAASC,cAAc;AAEvB,SAOEC,WAAW;;AAmBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AASA,SAASC,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAGL,cAAc,CAAC,CAAC;EAEpC,MAAMM,GAAG,GAAGT,MAAM,CAAiB,CAAC;EAEpC,IAAIU,EAAkB;EACtB,IAAI,CAACD,GAAG,CAACE,OAAO,EAAE;IAChB,MAAMC,OAAO,GAAG,IAAIV,OAAO,CAAC,CAAC;IAC7BO,GAAG,CAACE,OAAO,GAAG;MACZC,OAAO;MACPJ,WAAW;MACXF,IAAI;MACJO,MAAM,EAAGC,KAAK,IAAK;QACjB,MAAMC,QAAQ,GAAGj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B,oBAAoB,CAC7BS,EAAE,CAACiB,SAAS,EACZ,MAAMjB,EAAE,CAAEF,WAAW,CAACQ,GAAG,CAAkBN,EAAE,CAAEJ,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMG,EAAE,CAAEF,WAAW,CAACQ,GAAG,CACvBN,EAAE,CAAEJ,IAAI,EACR;IAAEC,YAAY;IAAEwB,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAEDhC,SAAS,CAAC,MAAM;IACd,MAAM;MAAE+B;IAAQ,CAAC,GAAGrB,GAAG,CAACE,OAAQ;IAChCH,WAAW,CAACwB,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAMtB,WAAW,CAACyB,OAAO,CAACH,OAAO,CAAC;EAC3C,CAAC,EAAE,CAACtB,WAAW,CAAC,CAAC;EAEjBT,SAAS,CAAC,MAAM;IACdU,GAAG,CAACE,OAAO,CAAEmB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACxB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACI,EAAE,CAACe,KAAK,EAAEf,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc","ignoreList":[]}
|
package/build/types/index.d.ts
CHANGED
|
@@ -2,13 +2,13 @@ import GlobalState from './GlobalState';
|
|
|
2
2
|
import GlobalStateProvider, { getGlobalState, getSsrContext } from './GlobalStateProvider';
|
|
3
3
|
import SsrContext from './SsrContext';
|
|
4
4
|
import useAsyncCollection, { type UseAsyncCollectionI } from './useAsyncCollection';
|
|
5
|
-
import
|
|
5
|
+
import { type UseAsyncDataI, newAsyncDataEnvelope } from './useAsyncData';
|
|
6
6
|
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
7
7
|
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
8
|
-
export
|
|
8
|
+
export * from './useAsyncData';
|
|
9
9
|
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
10
10
|
export type { ForceT, ValueOrInitializerT } from './utils';
|
|
11
|
-
export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider,
|
|
11
|
+
export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, SsrContext, useAsyncCollection, useGlobalState, };
|
|
12
12
|
interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
|
|
13
13
|
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
14
14
|
getSsrContext: typeof getSsrContext<SsrContextT>;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { type ForceT, type LockT, type TypeLock, type ValueAtPathT } from './utils';
|
|
5
5
|
export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
6
|
+
export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
|
|
6
7
|
export type AsyncDataEnvelopeT<DataT> = {
|
|
7
8
|
data: null | DataT;
|
|
8
9
|
numRefs: number;
|
|
@@ -23,7 +24,7 @@ export type UseAsyncDataOptionsT = {
|
|
|
23
24
|
export type UseAsyncDataResT<DataT> = {
|
|
24
25
|
data: DataT | null;
|
|
25
26
|
loading: boolean;
|
|
26
|
-
reload:
|
|
27
|
+
reload: AsyncDataReloaderT<DataT>;
|
|
27
28
|
timestamp: number;
|
|
28
29
|
};
|
|
29
30
|
/**
|
|
@@ -76,7 +77,7 @@ export type UseAsyncDataResT<DataT> = {
|
|
|
76
77
|
export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
|
|
77
78
|
declare function useAsyncData<StateT, PathT extends null | string | undefined, DataT extends DataInEnvelopeAtPathT<StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>>(path: PathT, loader: AsyncDataLoaderT<DataT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT>;
|
|
78
79
|
declare function useAsyncData<Forced extends ForceT | LockT = LockT, DataT = void>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
79
|
-
export
|
|
80
|
+
export { useAsyncData };
|
|
80
81
|
export interface UseAsyncDataI<StateT> {
|
|
81
82
|
<PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
82
83
|
<Forced extends ForceT | LockT = LockT, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.2",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
5
|
"main": "./build/common/index.js",
|
|
6
6
|
"react-native": "src/index.ts",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"build:types": "rimraf build/types && tsc --project tsconfig.types.json",
|
|
19
19
|
"jest": "npm run jest:types && npm run jest:logic",
|
|
20
20
|
"jest:logic": "jest --config jest/config.json -w 1",
|
|
21
|
-
"jest:types": "
|
|
21
|
+
"jest:types": "tstyche",
|
|
22
22
|
"lint": "eslint --ext .js,.jsx,.ts,.tsx .",
|
|
23
23
|
"test": "npm run lint && npm run typecheck && npm run jest",
|
|
24
24
|
"typecheck": "tsc --project __tests__/tsconfig.json"
|
|
@@ -43,30 +43,28 @@
|
|
|
43
43
|
"node": ">=18"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@babel/runtime": "^7.24.
|
|
47
|
-
"@dr.pogodin/js-utils": "^0.0.
|
|
48
|
-
"@types/lodash": "^4.17.
|
|
46
|
+
"@babel/runtime": "^7.24.6",
|
|
47
|
+
"@dr.pogodin/js-utils": "^0.0.12",
|
|
48
|
+
"@types/lodash": "^4.17.4",
|
|
49
49
|
"lodash": "^4.17.21",
|
|
50
50
|
"uuid": "^9.0.1"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@babel/cli": "^7.24.
|
|
54
|
-
"@babel/core": "^7.24.
|
|
55
|
-
"@babel/eslint-parser": "^7.24.
|
|
56
|
-
"@babel/eslint-plugin": "^7.24.
|
|
57
|
-
"@babel/node": "^7.
|
|
58
|
-
"@babel/plugin-transform-runtime": "^7.24.
|
|
59
|
-
"@babel/preset-env": "^7.24.
|
|
60
|
-
"@babel/preset-react": "^7.24.
|
|
61
|
-
"@babel/preset-typescript": "^7.24.
|
|
53
|
+
"@babel/cli": "^7.24.6",
|
|
54
|
+
"@babel/core": "^7.24.6",
|
|
55
|
+
"@babel/eslint-parser": "^7.24.6",
|
|
56
|
+
"@babel/eslint-plugin": "^7.24.6",
|
|
57
|
+
"@babel/node": "^7.24.6",
|
|
58
|
+
"@babel/plugin-transform-runtime": "^7.24.6",
|
|
59
|
+
"@babel/preset-env": "^7.24.6",
|
|
60
|
+
"@babel/preset-react": "^7.24.6",
|
|
61
|
+
"@babel/preset-typescript": "^7.24.6",
|
|
62
62
|
"@tsconfig/recommended": "^1.0.6",
|
|
63
|
-
"@tsd/typescript": "^5.4.5",
|
|
64
63
|
"@types/jest": "^29.5.12",
|
|
65
64
|
"@types/pretty": "^2.0.3",
|
|
66
|
-
"@types/react": "^18.3.
|
|
65
|
+
"@types/react": "^18.3.3",
|
|
67
66
|
"@types/react-dom": "^18.3.0",
|
|
68
67
|
"@types/uuid": "^9.0.8",
|
|
69
|
-
"typescript-eslint": "^7.8.0",
|
|
70
68
|
"babel-jest": "^29.7.0",
|
|
71
69
|
"babel-plugin-module-resolver": "^5.0.2",
|
|
72
70
|
"eslint": "^8.57.0",
|
|
@@ -76,16 +74,16 @@
|
|
|
76
74
|
"eslint-plugin-import": "^2.29.1",
|
|
77
75
|
"eslint-plugin-jest": "^28.5.0",
|
|
78
76
|
"eslint-plugin-jsx-a11y": "^6.8.0",
|
|
79
|
-
"eslint-plugin-react": "^7.34.
|
|
77
|
+
"eslint-plugin-react": "^7.34.2",
|
|
80
78
|
"eslint-plugin-react-hooks": "^4.6.2",
|
|
81
79
|
"jest": "^29.7.0",
|
|
82
80
|
"jest-environment-jsdom": "^29.7.0",
|
|
83
|
-
"jest-runner-tsd": "^6.0.0",
|
|
84
81
|
"mockdate": "^3.0.5",
|
|
85
82
|
"pretty": "^2.0.0",
|
|
86
|
-
"rimraf": "^5.0.
|
|
87
|
-
"
|
|
88
|
-
"typescript": "^5.4.5"
|
|
83
|
+
"rimraf": "^5.0.7",
|
|
84
|
+
"tstyche": "^1.1.0",
|
|
85
|
+
"typescript": "^5.4.5",
|
|
86
|
+
"typescript-eslint": "^7.11.0"
|
|
89
87
|
},
|
|
90
88
|
"peerDependencies": {
|
|
91
89
|
"react": "^18.3.1",
|
package/src/index.ts
CHANGED
|
@@ -11,21 +11,17 @@ import useAsyncCollection, {
|
|
|
11
11
|
type UseAsyncCollectionI,
|
|
12
12
|
} from './useAsyncCollection';
|
|
13
13
|
|
|
14
|
-
import
|
|
14
|
+
import {
|
|
15
15
|
type UseAsyncDataI,
|
|
16
16
|
newAsyncDataEnvelope,
|
|
17
|
+
useAsyncData,
|
|
17
18
|
} from './useAsyncData';
|
|
18
19
|
|
|
19
20
|
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
20
21
|
|
|
21
22
|
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
22
23
|
|
|
23
|
-
export
|
|
24
|
-
AsyncDataEnvelopeT,
|
|
25
|
-
AsyncDataLoaderT,
|
|
26
|
-
UseAsyncDataOptionsT,
|
|
27
|
-
UseAsyncDataResT,
|
|
28
|
-
} from './useAsyncData';
|
|
24
|
+
export * from './useAsyncData';
|
|
29
25
|
|
|
30
26
|
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
31
27
|
|
|
@@ -36,10 +32,8 @@ export {
|
|
|
36
32
|
getSsrContext,
|
|
37
33
|
GlobalState,
|
|
38
34
|
GlobalStateProvider,
|
|
39
|
-
newAsyncDataEnvelope,
|
|
40
35
|
SsrContext,
|
|
41
36
|
useAsyncCollection,
|
|
42
|
-
useAsyncData,
|
|
43
37
|
useGlobalState,
|
|
44
38
|
};
|
|
45
39
|
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Loads and uses an item in an async collection.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import {
|
|
6
6
|
type DataInEnvelopeAtPathT,
|
|
7
7
|
type UseAsyncDataOptionsT,
|
|
8
8
|
type UseAsyncDataResT,
|
|
9
|
+
useAsyncData,
|
|
9
10
|
} from './useAsyncData';
|
|
10
11
|
|
|
11
12
|
import { type ForceT, type LockT, type TypeLock } from './utils';
|
package/src/useAsyncData.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { cloneDeep } from 'lodash';
|
|
6
|
-
import { useEffect } from 'react';
|
|
6
|
+
import { useEffect, useRef } from 'react';
|
|
7
7
|
import { v4 as uuid } from 'uuid';
|
|
8
8
|
|
|
9
9
|
import { MIN_MS } from '@dr.pogodin/js-utils';
|
|
@@ -27,6 +27,9 @@ const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
|
|
|
27
27
|
export type AsyncDataLoaderT<DataT>
|
|
28
28
|
= (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
29
29
|
|
|
30
|
+
export type AsyncDataReloaderT<DataT>
|
|
31
|
+
= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;
|
|
32
|
+
|
|
30
33
|
export type AsyncDataEnvelopeT<DataT> = {
|
|
31
34
|
data: null | DataT;
|
|
32
35
|
numRefs: number;
|
|
@@ -57,7 +60,7 @@ export type UseAsyncDataOptionsT = {
|
|
|
57
60
|
export type UseAsyncDataResT<DataT> = {
|
|
58
61
|
data: DataT | null;
|
|
59
62
|
loading: boolean;
|
|
60
|
-
reload:
|
|
63
|
+
reload: AsyncDataReloaderT<DataT>;
|
|
61
64
|
timestamp: number;
|
|
62
65
|
};
|
|
63
66
|
|
|
@@ -92,9 +95,14 @@ async function load<DataT>(
|
|
|
92
95
|
const operationId = opIdPrefix + uuid();
|
|
93
96
|
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
94
97
|
globalState.set<ForceT, string>(operationIdPath, operationId);
|
|
95
|
-
|
|
98
|
+
|
|
99
|
+
const dataOrLoader = loader(
|
|
96
100
|
oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,
|
|
97
101
|
);
|
|
102
|
+
|
|
103
|
+
const data: DataT = dataOrLoader instanceof Promise
|
|
104
|
+
? await dataOrLoader : dataOrLoader;
|
|
105
|
+
|
|
98
106
|
const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);
|
|
99
107
|
if (operationId === state.operationId) {
|
|
100
108
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
@@ -174,6 +182,14 @@ export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefine
|
|
|
174
182
|
? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>
|
|
175
183
|
: void;
|
|
176
184
|
|
|
185
|
+
type HeapT<DataT> = {
|
|
186
|
+
// Note: these heap fields are necessary to make reload() a stable function.
|
|
187
|
+
globalState?: GlobalState<unknown>;
|
|
188
|
+
path?: null | string;
|
|
189
|
+
loader?: AsyncDataLoaderT<DataT>;
|
|
190
|
+
reload?: AsyncDataReloaderT<DataT>;
|
|
191
|
+
};
|
|
192
|
+
|
|
177
193
|
function useAsyncData<
|
|
178
194
|
StateT,
|
|
179
195
|
PathT extends null | string | undefined,
|
|
@@ -216,6 +232,19 @@ function useAsyncData<DataT>(
|
|
|
216
232
|
initialValue: newAsyncDataEnvelope<DataT>(),
|
|
217
233
|
});
|
|
218
234
|
|
|
235
|
+
const { current: heap } = useRef<HeapT<DataT>>({});
|
|
236
|
+
heap.globalState = globalState;
|
|
237
|
+
heap.path = path;
|
|
238
|
+
heap.loader = loader;
|
|
239
|
+
|
|
240
|
+
if (!heap.reload) {
|
|
241
|
+
heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {
|
|
242
|
+
const localLoader = customLoader || heap.loader;
|
|
243
|
+
if (!localLoader || !heap.globalState) throw Error('Internal error');
|
|
244
|
+
return load(heap.path, localLoader, heap.globalState, null);
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
219
248
|
if (globalState.ssrContext && !options.noSSR) {
|
|
220
249
|
if (!state.timestamp && !state.operationId) {
|
|
221
250
|
globalState.ssrContext.pending.push(
|
|
@@ -301,19 +330,12 @@ function useAsyncData<DataT>(
|
|
|
301
330
|
return {
|
|
302
331
|
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
303
332
|
loading: Boolean(localState.operationId),
|
|
304
|
-
|
|
305
|
-
reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(
|
|
306
|
-
path,
|
|
307
|
-
customLoader || loader,
|
|
308
|
-
globalState,
|
|
309
|
-
null,
|
|
310
|
-
),
|
|
311
|
-
|
|
333
|
+
reload: heap.reload,
|
|
312
334
|
timestamp: localState.timestamp,
|
|
313
335
|
};
|
|
314
336
|
}
|
|
315
337
|
|
|
316
|
-
export
|
|
338
|
+
export { useAsyncData };
|
|
317
339
|
|
|
318
340
|
export interface UseAsyncDataI<StateT> {
|
|
319
341
|
<PathT extends null | string | undefined>(
|
package/tsconfig.json
CHANGED