@dr.pogodin/react-global-state 0.10.0-alpha.2 → 0.10.0-alpha.4

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.
Files changed (63) hide show
  1. package/README.md +2 -0
  2. package/build/common/GlobalState.js +219 -0
  3. package/build/common/GlobalState.js.map +1 -0
  4. package/build/common/GlobalStateProvider.js +101 -0
  5. package/build/common/GlobalStateProvider.js.map +1 -0
  6. package/build/common/SsrContext.js +15 -0
  7. package/build/common/SsrContext.js.map +1 -0
  8. package/build/common/index.js +81 -0
  9. package/build/common/index.js.map +1 -0
  10. package/build/common/useAsyncCollection.js +61 -0
  11. package/build/common/useAsyncCollection.js.map +1 -0
  12. package/build/common/useAsyncData.js +204 -0
  13. package/build/common/useAsyncData.js.map +1 -0
  14. package/build/common/useGlobalState.js +114 -0
  15. package/build/common/useGlobalState.js.map +1 -0
  16. package/build/common/utils.js +43 -0
  17. package/build/common/utils.js.map +1 -0
  18. package/build/module/GlobalState.js +230 -0
  19. package/build/module/GlobalState.js.map +1 -0
  20. package/build/module/GlobalStateProvider.js +94 -0
  21. package/build/module/GlobalStateProvider.js.map +1 -0
  22. package/build/module/SsrContext.js +9 -0
  23. package/build/module/SsrContext.js.map +1 -0
  24. package/build/module/index.js +19 -0
  25. package/build/module/index.js.map +1 -0
  26. package/build/module/useAsyncCollection.js +56 -0
  27. package/build/module/useAsyncCollection.js.map +1 -0
  28. package/build/module/useAsyncData.js +199 -0
  29. package/build/module/useAsyncData.js.map +1 -0
  30. package/build/module/useGlobalState.js +109 -0
  31. package/build/module/useGlobalState.js.map +1 -0
  32. package/build/module/utils.js +35 -0
  33. package/build/module/utils.js.map +1 -0
  34. package/build/{GlobalState.d.ts → types/GlobalState.d.ts} +6 -6
  35. package/build/{GlobalStateProvider.d.ts → types/GlobalStateProvider.d.ts} +8 -8
  36. package/build/types/index.d.ts +24 -0
  37. package/build/{useAsyncCollection.d.ts → types/useAsyncCollection.d.ts} +6 -2
  38. package/build/{useAsyncData.d.ts → types/useAsyncData.d.ts} +6 -3
  39. package/build/{useGlobalState.d.ts → types/useGlobalState.d.ts} +7 -2
  40. package/build/{utils.d.ts → types/utils.d.ts} +6 -1
  41. package/package.json +43 -38
  42. package/src/GlobalState.ts +15 -10
  43. package/src/GlobalStateProvider.tsx +26 -15
  44. package/src/index.ts +57 -19
  45. package/src/useAsyncCollection.ts +21 -5
  46. package/src/useAsyncData.ts +43 -20
  47. package/src/useGlobalState.ts +30 -11
  48. package/src/utils.ts +11 -3
  49. package/tsconfig.json +10 -4
  50. package/tsconfig.types.json +14 -0
  51. package/build/GlobalState.js +0 -193
  52. package/build/GlobalStateProvider.js +0 -103
  53. package/build/SsrContext.js +0 -10
  54. package/build/index.d.ts +0 -8
  55. package/build/index.js +0 -23
  56. package/build/useAsyncCollection.js +0 -14
  57. package/build/useAsyncData.js +0 -150
  58. package/build/useGlobalState.js +0 -49
  59. package/build/utils.js +0 -25
  60. package/build/withGlobalStateType.d.ts +0 -39
  61. package/build/withGlobalStateType.js +0 -55
  62. package/src/withGlobalStateType.ts +0 -118
  63. /package/build/{SsrContext.d.ts → types/SsrContext.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalState.js","names":["cloneDeep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_initialState","WeakMap","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","writable","value","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","path","p","setTimeout","watchers","i","length","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 #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 * 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,SAAA,oBAAAD,OAAA;AAAA,IAAAE,eAAA,oBAAAF,OAAA;AAAA,IAAAG,aAAA,oBAAAH,OAAA;AAO1E,eAAe,MAAMI,WAAW,CAG9B;EAeA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAAAC,0BAAA,OAAAT,aA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ACzB;EACF;AACF"}
@@ -0,0 +1,94 @@
1
+ /* eslint-disable react/prop-types */
2
+
3
+ import { isFunction } from 'lodash';
4
+ import { createContext, useContext, useRef } from 'react';
5
+ import GlobalState from "./GlobalState";
6
+ import { jsx as _jsx } from "react/jsx-runtime";
7
+ const context = /*#__PURE__*/createContext(null);
8
+
9
+ /**
10
+ * Gets {@link GlobalState} instance from the context. In most cases
11
+ * you should use {@link useGlobalState}, and other hooks to interact with
12
+ * the global state, instead of accessing it directly.
13
+ * @return
14
+ */
15
+ export function getGlobalState() {
16
+ // Here Rules of Hooks are violated because "getGlobalState()" does not follow
17
+ // convention that hook names should start with use... This is intentional in
18
+ // our case, as getGlobalState() hook is intended for advance scenarious,
19
+ // while the normal interaction with the global state should happen via
20
+ // another hook, useGlobalState().
21
+ /* eslint-disable react-hooks/rules-of-hooks */
22
+ const globalState = useContext(context);
23
+ /* eslint-enable react-hooks/rules-of-hooks */
24
+ if (!globalState) throw new Error('Missing GlobalStateProvider');
25
+ return globalState;
26
+ }
27
+
28
+ /**
29
+ * @category Hooks
30
+ * @desc Gets SSR context.
31
+ * @param throwWithoutSsrContext If `true` (default),
32
+ * this hook will throw if no SSR context is attached to the global state;
33
+ * set `false` to not throw in such case. In either case the hook will throw
34
+ * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
35
+ * @returns SSR context.
36
+ * @throws
37
+ * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
38
+ * in the rendered React tree.
39
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
40
+ * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
41
+ */
42
+ export function getSsrContext() {
43
+ let throwWithoutSsrContext = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
44
+ const {
45
+ ssrContext
46
+ } = getGlobalState();
47
+ if (!ssrContext && throwWithoutSsrContext) {
48
+ throw new Error('No SSR context found');
49
+ }
50
+ return ssrContext;
51
+ }
52
+ /**
53
+ * Provides global state to its children.
54
+ * @param prop.children Component children, which will be provided with
55
+ * the global state, and rendered in place of the provider.
56
+ * @param prop.initialState Initial content of the global state.
57
+ * @param prop.ssrContext Server-side rendering (SSR) context.
58
+ * @param prop.stateProxy This option is useful for code
59
+ * splitting and SSR implementation:
60
+ * - If `true`, this provider instance will fetch and reuse the global state
61
+ * from a parent provider.
62
+ * - If `GlobalState` instance, it will be used by this provider.
63
+ * - If not given, a new `GlobalState` instance will be created and used.
64
+ */
65
+ export default function GlobalStateProvider(_ref) {
66
+ let {
67
+ children,
68
+ ...rest
69
+ } = _ref;
70
+ const state = useRef();
71
+ if (!state.current) {
72
+ // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
73
+ // graceful compatibility with JavaScript - if "undefined" stateProxy value
74
+ // is given, we want to follow the second branch, which creates a new
75
+ // GlobalState with whatever intiialState given.
76
+ if ('stateProxy' in rest && rest.stateProxy) {
77
+ if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
78
+ } else {
79
+ const {
80
+ initialState,
81
+ ssrContext
82
+ } = rest;
83
+ state.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
84
+ }
85
+ }
86
+ return /*#__PURE__*/_jsx(context.Provider, {
87
+ value: state.current,
88
+ children: children
89
+ });
90
+ }
91
+ GlobalStateProvider.defaultProps = {
92
+ children: undefined
93
+ };
94
+ //# sourceMappingURL=GlobalStateProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value","defaultProps"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n\nGlobalStateProvider.defaultProps = {\n children: undefined,\n};\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAA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DR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAF,mBAAmB,CAACU,YAAY,GAAG;EACjCR,QAAQ,EAAEJ;AACZ,CAAC"}
@@ -0,0 +1,9 @@
1
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
+ export default class SsrContext {
3
+ constructor(state) {
4
+ _defineProperty(this, "dirty", false);
5
+ _defineProperty(this, "pending", []);
6
+ this.state = state;
7
+ }
8
+ }
9
+ //# sourceMappingURL=SsrContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SsrContext.js","names":["SsrContext","constructor","state","_defineProperty"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAOtCC,WAAWA,CAACC,KAAc,EAAE;IAAAC,eAAA,gBANX,KAAK;IAAAA,eAAA,kBAEK,EAAE;IAK3B,IAAI,CAACD,KAAK,GAAGA,KAAK;EACpB;AACF"}
@@ -0,0 +1,19 @@
1
+ import GlobalState from "./GlobalState";
2
+ import GlobalStateProvider, { getGlobalState, getSsrContext } from "./GlobalStateProvider";
3
+ import SsrContext from "./SsrContext";
4
+ import useAsyncCollection from "./useAsyncCollection";
5
+ import useAsyncData, { newAsyncDataEnvelope } from "./useAsyncData";
6
+ import useGlobalState from "./useGlobalState";
7
+ export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState };
8
+ export default {
9
+ getGlobalState,
10
+ getSsrContext,
11
+ GlobalState,
12
+ GlobalStateProvider,
13
+ newAsyncDataEnvelope,
14
+ SsrContext,
15
+ useAsyncCollection,
16
+ useAsyncData,
17
+ useGlobalState
18
+ };
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","useAsyncData","newAsyncDataEnvelope","useGlobalState"],"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 useAsyncData, {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type {\n AsyncDataEnvelopeT,\n AsyncDataLoaderT,\n UseAsyncDataOptionsT,\n UseAsyncDataResT,\n} 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 newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport interface 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\nexport default {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n} as API<unknown>;\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAIzB,OAAOC,YAAY,IAEjBC,oBAAoB;AAGtB,OAAOC,cAAc;AAerB,SACEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBM,oBAAoB,EACpBH,UAAU,EACVC,kBAAkB,EAClBC,YAAY,EACZE,cAAc;AAkBhB,eAAe;EACbN,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBM,oBAAoB;EACpBH,UAAU;EACVC,kBAAkB;EAClBC,YAAY;EACZE;AACF,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Loads and uses an item in an async collection.
3
+ */
4
+
5
+ import useAsyncData from "./useAsyncData";
6
+
7
+ /**
8
+ * Resolves and stores at the given `path` of global state elements of
9
+ * an asynchronous data collection. In other words, it is an auxiliar wrapper
10
+ * around {@link useAsyncData}, which uses a loader which resolves to different
11
+ * data, based on ID argument passed in, and stores data fetched for different
12
+ * IDs in the state.
13
+ * @param id ID of the collection item to load & use.
14
+ * @param path The global state path where entire collection should be
15
+ * stored.
16
+ * @param loader A loader function, which takes an
17
+ * ID of data to load, and resolves to the corresponding data.
18
+ * @param options Additional options.
19
+ * @param options.deps An array of dependencies, which trigger
20
+ * data reload when changed. Given dependency changes are watched shallowly
21
+ * (similarly to the standard React's
22
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
23
+ * @param options.noSSR If `true`, this hook won't load data during
24
+ * server-side rendering.
25
+ * @param options.garbageCollectAge The maximum age of data
26
+ * (in milliseconds), after which they are dropped from the state when the last
27
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
28
+ * `maxage` option value.
29
+ * @param options.maxage The maximum age of
30
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
31
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
32
+ * @param options.refreshAge The maximum age of data
33
+ * (in milliseconds), after which their refreshment will be triggered when
34
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
35
+ * Defaults to `maxage` value.
36
+ * @return Returns an object with three fields: `data` holds the actual result of
37
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
38
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
39
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
40
+ * is Unix timestamp of related data currently loaded into the global state.
41
+ *
42
+ * Note that loaded data, if any, are stored at the given `path` of global state
43
+ * along with related meta-information, using slightly different state segment
44
+ * structure (see {@link AsyncDataEnvelope}). That segment of the global state
45
+ * can be accessed, and even modified using other hooks,
46
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
47
+ * `useAsyncData()` hooks logic.
48
+ */
49
+
50
+ function useAsyncCollection(id, path, loader) {
51
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
52
+ const itemPath = path ? `${path}.${id}` : id;
53
+ return useAsyncData(itemPath, oldData => loader(id, oldData), options);
54
+ }
55
+ export default useAsyncCollection;
56
+ //# sourceMappingURL=useAsyncCollection.js.map
@@ -0,0 +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 useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\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 id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>\n >,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\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,OAAOA,YAAY;;AAWnB;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;;AAyBA,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,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB"}
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Loads and uses async data into the GlobalState path.
3
+ */
4
+
5
+ import { cloneDeep } from 'lodash';
6
+ import { useEffect } from 'react';
7
+ import { v4 as uuid } from 'uuid';
8
+ import { MIN_MS } from '@dr.pogodin/js-utils';
9
+ import { getGlobalState } from "./GlobalStateProvider";
10
+ import useGlobalState from "./useGlobalState";
11
+ import { isDebugMode } from "./utils";
12
+ const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
13
+
14
+ export function newAsyncDataEnvelope() {
15
+ let initialData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
16
+ return {
17
+ data: initialData,
18
+ numRefs: 0,
19
+ operationId: '',
20
+ timestamp: 0
21
+ };
22
+ }
23
+ /**
24
+ * Executes the data loading operation.
25
+ * @param path Data segment path inside the global state.
26
+ * @param loader Data loader.
27
+ * @param globalState The global state instance.
28
+ * @param oldData Optional. Previously fetched data, currently stored in
29
+ * the state, if already fetched by the caller; otherwise, they will be fetched
30
+ * by the load() function itself.
31
+ * @param opIdPrefix operationId prefix to use, which should be
32
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
33
+ * context).
34
+ * @return Resolves once the operation is done.
35
+ * @ignore
36
+ */
37
+ async function load(path, loader, globalState, oldData) {
38
+ let opIdPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'C';
39
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
40
+ /* eslint-disable no-console */
41
+ console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
42
+ /* eslint-enable no-console */
43
+ }
44
+
45
+ const operationId = opIdPrefix + uuid();
46
+ const operationIdPath = path ? `${path}.operationId` : 'operationId';
47
+ globalState.set(operationIdPath, operationId);
48
+ const data = await loader(oldData || globalState.get(path).data);
49
+ const state = globalState.get(path);
50
+ if (operationId === state.operationId) {
51
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
52
+ /* eslint-disable no-console */
53
+ console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
54
+ console.log('Data:', cloneDeep(data));
55
+ /* eslint-enable no-console */
56
+ }
57
+
58
+ globalState.set(path, {
59
+ ...state,
60
+ data,
61
+ operationId: '',
62
+ timestamp: Date.now()
63
+ });
64
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
65
+ /* eslint-disable no-console */
66
+ console.groupEnd();
67
+ /* eslint-enable no-console */
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Resolves asynchronous data, and stores them at given `path` of global
74
+ * state. When multiple components rely on asynchronous data at the same `path`,
75
+ * the data are resolved once, and reused until their age is within specified
76
+ * bounds. Once the data are stale, the hook allows to refresh them. It also
77
+ * garbage-collects stale data from the global state when the last component
78
+ * relying on them is unmounted.
79
+ * @param path Dot-delimitered state path, where data envelop is
80
+ * stored.
81
+ * @param loader Asynchronous function which resolves (loads)
82
+ * data, which should be stored at the global state `path`. When multiple
83
+ * components
84
+ * use `useAsyncData()` hook for the same `path`, the library assumes that all
85
+ * hook instances are called with the same `loader` (_i.e._ whichever of these
86
+ * loaders is used to resolve async data, the result is acceptable to be reused
87
+ * in all related components).
88
+ * @param options Additional options.
89
+ * @param options.deps An array of dependencies, which trigger
90
+ * data reload when changed. Given dependency changes are watched shallowly
91
+ * (similarly to the standard React's
92
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
93
+ * @param options.noSSR If `true`, this hook won't load data during
94
+ * server-side rendering.
95
+ * @param options.garbageCollectAge The maximum age of data
96
+ * (in milliseconds), after which they are dropped from the state when the last
97
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
98
+ * `maxage` option value.
99
+ * @param options.maxage The maximum age of
100
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
101
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
102
+ * @param options.refreshAge The maximum age of data
103
+ * (in milliseconds), after which their refreshment will be triggered when
104
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
105
+ * Defaults to `maxage` value.
106
+ * @return Returns an object with three fields: `data` holds the actual result of
107
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
108
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
109
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
110
+ * is Unix timestamp of related data currently loaded into the global state.
111
+ *
112
+ * Note that loaded data, if any, are stored at the given `path` of global state
113
+ * along with related meta-information, using slightly different state segment
114
+ * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
115
+ * can be accessed, and even modified using other hooks,
116
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
117
+ * `useAsyncData()` hooks logic.
118
+ */
119
+
120
+ function useAsyncData(path, loader) {
121
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
122
+ const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
123
+ const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
124
+ const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
125
+
126
+ // Note: here we can't depend on useGlobalState() to init the initial value,
127
+ // because that way we'll have issues with SSR (see details below).
128
+ const globalState = getGlobalState();
129
+ const state = globalState.get(path, {
130
+ initialValue: newAsyncDataEnvelope()
131
+ });
132
+ if (globalState.ssrContext && !options.noSSR) {
133
+ if (!state.timestamp && !state.operationId) {
134
+ globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
135
+ }
136
+ } else {
137
+ // This takes care about the client-side reference counting, and garbage
138
+ // collection.
139
+ //
140
+ // Note: the Rules of Hook below are violated by conditional call to a hook,
141
+ // but as the condition is actually server-side or client-side environment,
142
+ // it is effectively non-conditional at the runtime.
143
+ //
144
+ // TODO: Though, maybe there is a way to refactor it into a cleaner code.
145
+ // The same applies to other useEffect() hooks below.
146
+ useEffect(() => {
147
+ // eslint-disable-line react-hooks/rules-of-hooks
148
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
149
+ const numRefs = globalState.get(numRefsPath);
150
+ globalState.set(numRefsPath, numRefs + 1);
151
+ return () => {
152
+ const state2 = globalState.get(path);
153
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
154
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
155
+ /* eslint-disable no-console */
156
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
157
+ /* eslint-enable no-console */
158
+ }
159
+
160
+ globalState.set(path, {
161
+ ...state2,
162
+ data: null,
163
+ numRefs: 0,
164
+ timestamp: 0
165
+ });
166
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
167
+ };
168
+ }, [garbageCollectAge, globalState, path]);
169
+
170
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
171
+ // special case the otherwise wrong behavior is actually what we need.
172
+
173
+ // Data loading and refreshing.
174
+ let loadTriggered = false;
175
+ useEffect(() => {
176
+ // eslint-disable-line react-hooks/rules-of-hooks
177
+ const state2 = globalState.get(path);
178
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
179
+ load(path, loader, globalState, state2.data);
180
+ loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
181
+ }
182
+ });
183
+
184
+ const deps = options.deps || [];
185
+ useEffect(() => {
186
+ // eslint-disable-line react-hooks/rules-of-hooks
187
+ if (!loadTriggered && deps.length) load(path, loader, globalState, null);
188
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
189
+ }
190
+
191
+ const [localState] = useGlobalState(path, newAsyncDataEnvelope());
192
+ return {
193
+ data: maxage < Date.now() - localState.timestamp ? null : localState.data,
194
+ loading: Boolean(localState.operationId),
195
+ timestamp: localState.timestamp
196
+ };
197
+ }
198
+ export default useAsyncData;
199
+ //# sourceMappingURL=useAsyncData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","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","loadTriggered","charAt","deps","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 } 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): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\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 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 path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\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.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 const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, 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 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,EAEP;EAAA,IAD3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAEhC,OAAO;IACLG,IAAI,EAAEJ,WAAW;IACjBK,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,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,WAAW,CAAC,CAAC,EAAE;IAC1D;IACAoB,OAAO,CAACC,GAAG,CACR,4DAA2D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QAC5CmC,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;;IAEF,MAAME,IAAI,GAAGb,OAAO,CAACa,IAAI,IAAI,EAAE;IAC/BlD,SAAS,CAAC,MAAM;MAAE;MAChB,IAAI,CAACgD,aAAa,IAAIE,IAAI,CAACvC,MAAM,EAAEM,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;IAC1E,CAAC,EAAE8B,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACC,UAAU,CAAC,GAAG9C,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLK,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGiB,UAAU,CAACnC,SAAS,GAAG,IAAI,GAAGmC,UAAU,CAACtC,IAAI;IACzEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpC,WAAW,CAAC;IACxCC,SAAS,EAAEmC,UAAU,CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
@@ -0,0 +1,109 @@
1
+ // Hook for updates of global state.
2
+
3
+ import { cloneDeep, isFunction } from 'lodash';
4
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
5
+ import { Emitter } from '@dr.pogodin/js-utils';
6
+ import { getGlobalState } from "./GlobalStateProvider";
7
+ import { isDebugMode } from "./utils";
8
+
9
+ /**
10
+ * The primary hook for interacting with the global state, modeled after
11
+ * the standard React's
12
+ * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
13
+ * It subscribes a component to a given `path` of global state, and provides
14
+ * a function to update it. Each time the value at `path` changes, the hook
15
+ * triggers re-render of its host component.
16
+ *
17
+ * **Note:**
18
+ * - For performance, the library does not copy objects written to / read from
19
+ * global state paths. You MUST NOT manually mutate returned state values,
20
+ * or change objects already written into the global state, without explicitly
21
+ * clonning them first yourself.
22
+ * - State update notifications are asynchronous. When your code does multiple
23
+ * global state updates in the same React rendering cycle, all state update
24
+ * notifications are queued and dispatched together, after the current
25
+ * rendering cycle. In other words, in any given rendering cycle the global
26
+ * state values are "fixed", and all changes becomes visible at once in the
27
+ * next triggered rendering pass.
28
+ *
29
+ * @param path Dot-delimitered state path. It can be undefined to
30
+ * subscribe for entire state.
31
+ *
32
+ * Under-the-hood state values are read and written using `lodash`
33
+ * [_.get()](https://lodash.com/docs/4.17.15#get) and
34
+ * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
35
+ * to access state paths which have not been created before.
36
+ * @param initialValue Initial value to set at the `path`, or its
37
+ * factory:
38
+ * - If a function is given, it will act similar to
39
+ * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
40
+ * only if the value at `path` is `undefined`, the function will be executed,
41
+ * and the value it returns will be written to the `path`.
42
+ * - Otherwise, the given value itself will be written to the `path`,
43
+ * if the current value at `path` is `undefined`.
44
+ * @return It returs an array with two elements: `[value, setValue]`:
45
+ *
46
+ * - The `value` is the current value at given `path`.
47
+ *
48
+ * - The `setValue()` is setter function to write a new value to the `path`.
49
+ *
50
+ * Similar to the standard React's `useState()`, it supports
51
+ * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
52
+ * if `setValue()` is called with a function as argument, that function will
53
+ * be called and its return value will be written to `path`. Otherwise,
54
+ * the argument of `setValue()` itself is written to `path`.
55
+ *
56
+ * Also, similar to the standard React's state setters, `setValue()` is
57
+ * stable function: it does not change between component re-renders.
58
+ */ // "Enforced type overload"
59
+ // "Entire state overload"
60
+ // "State evaluation overload"
61
+ function useGlobalState(path, initialValue) {
62
+ const globalState = getGlobalState();
63
+ const ref = useRef();
64
+ const rc = ref.current || {
65
+ emitter: new Emitter(),
66
+ globalState,
67
+ path,
68
+ setter: value => {
69
+ const newState = isFunction(value) ? value(rc.state) : value;
70
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
71
+ /* eslint-disable no-console */
72
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
73
+ console.log('New value:', cloneDeep(newState));
74
+ console.groupEnd();
75
+ /* eslint-enable no-console */
76
+ }
77
+
78
+ rc.globalState.set(rc.path, newState);
79
+ },
80
+ state: isFunction(initialValue) ? initialValue() : initialValue,
81
+ watcher: () => {
82
+ const state = rc.globalState.get(rc.path);
83
+ if (state !== rc.state) rc.emitter.emit();
84
+ }
85
+ };
86
+ ref.current = rc;
87
+ rc.globalState = globalState;
88
+ rc.path = path;
89
+ rc.state = useSyncExternalStore(cb => rc.emitter.addListener(cb), () => rc.globalState.get(rc.path, {
90
+ initialValue
91
+ }), () => rc.globalState.get(rc.path, {
92
+ initialValue,
93
+ initialState: true
94
+ }));
95
+ useEffect(() => {
96
+ const {
97
+ watcher
98
+ } = ref.current;
99
+ globalState.watch(watcher);
100
+ watcher();
101
+ return () => globalState.unWatch(watcher);
102
+ }, [globalState]);
103
+ useEffect(() => {
104
+ ref.current.watcher();
105
+ }, [path]);
106
+ return [rc.state, rc.setter];
107
+ }
108
+ export default useGlobalState;
109
+ //# sourceMappingURL=useGlobalState.js.map