@dr.pogodin/react-global-state 0.10.0-alpha.1 → 0.10.0-alpha.3

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 (58) hide show
  1. package/README.md +3 -327
  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 +76 -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 +113 -0
  15. package/build/common/useGlobalState.js.map +1 -0
  16. package/build/common/utils.js +44 -0
  17. package/build/common/utils.js.map +1 -0
  18. package/build/common/withGlobalStateType.js +42 -0
  19. package/build/common/withGlobalStateType.js.map +1 -0
  20. package/build/module/GlobalState.js +230 -0
  21. package/build/module/GlobalState.js.map +1 -0
  22. package/build/module/GlobalStateProvider.js +94 -0
  23. package/build/module/GlobalStateProvider.js.map +1 -0
  24. package/build/module/SsrContext.js +9 -0
  25. package/build/module/SsrContext.js.map +1 -0
  26. package/build/module/index.js +8 -0
  27. package/build/module/index.js.map +1 -0
  28. package/build/module/useAsyncCollection.js +56 -0
  29. package/build/module/useAsyncCollection.js.map +1 -0
  30. package/build/module/useAsyncData.js +199 -0
  31. package/build/module/useAsyncData.js.map +1 -0
  32. package/build/module/useGlobalState.js +108 -0
  33. package/build/module/useGlobalState.js.map +1 -0
  34. package/build/module/utils.js +35 -0
  35. package/build/module/utils.js.map +1 -0
  36. package/build/module/withGlobalStateType.js +35 -0
  37. package/build/module/withGlobalStateType.js.map +1 -0
  38. package/build/types/GlobalState.d.ts +75 -0
  39. package/build/types/GlobalStateProvider.d.ts +55 -0
  40. package/build/types/SsrContext.d.ts +6 -0
  41. package/build/types/index.d.ts +8 -0
  42. package/build/types/useAsyncCollection.d.ts +51 -0
  43. package/build/types/useAsyncData.d.ts +75 -0
  44. package/build/types/useGlobalState.d.ts +58 -0
  45. package/build/types/utils.d.ts +34 -0
  46. package/build/types/withGlobalStateType.d.ts +29 -0
  47. package/package.json +42 -41
  48. package/src/GlobalState.ts +283 -0
  49. package/src/GlobalStateProvider.tsx +127 -0
  50. package/src/SsrContext.ts +11 -0
  51. package/src/index.ts +33 -0
  52. package/src/useAsyncCollection.ts +96 -0
  53. package/src/useAsyncData.ts +295 -0
  54. package/src/useGlobalState.ts +156 -0
  55. package/src/utils.ts +64 -0
  56. package/src/withGlobalStateType.ts +170 -0
  57. package/tsconfig.json +9 -3
  58. package/tsconfig.types.json +14 -0
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = GlobalStateProvider;
8
+ exports.getGlobalState = getGlobalState;
9
+ exports.getSsrContext = getSsrContext;
10
+ var _lodash = require("lodash");
11
+ var _react = require("react");
12
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
13
+ var _jsxRuntime = require("react/jsx-runtime");
14
+ /* eslint-disable react/prop-types */
15
+
16
+ const context = /*#__PURE__*/(0, _react.createContext)(null);
17
+
18
+ /**
19
+ * Gets {@link GlobalState} instance from the context. In most cases
20
+ * you should use {@link useGlobalState}, and other hooks to interact with
21
+ * the global state, instead of accessing it directly.
22
+ * @return
23
+ */
24
+ function getGlobalState() {
25
+ // Here Rules of Hooks are violated because "getGlobalState()" does not follow
26
+ // convention that hook names should start with use... This is intentional in
27
+ // our case, as getGlobalState() hook is intended for advance scenarious,
28
+ // while the normal interaction with the global state should happen via
29
+ // another hook, useGlobalState().
30
+ /* eslint-disable react-hooks/rules-of-hooks */
31
+ const globalState = (0, _react.useContext)(context);
32
+ /* eslint-enable react-hooks/rules-of-hooks */
33
+ if (!globalState) throw new Error('Missing GlobalStateProvider');
34
+ return globalState;
35
+ }
36
+
37
+ /**
38
+ * @category Hooks
39
+ * @desc Gets SSR context.
40
+ * @param throwWithoutSsrContext If `true` (default),
41
+ * this hook will throw if no SSR context is attached to the global state;
42
+ * set `false` to not throw in such case. In either case the hook will throw
43
+ * if the {@link <GlobalStateProvider>} (hence the state) is missing.
44
+ * @returns SSR context.
45
+ * @throws
46
+ * - If current component has no parent {@link <GlobalStateProvider>}
47
+ * in the rendered React tree.
48
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
49
+ * to the global state provided by {@link <GlobalStateProvider>}.
50
+ */
51
+ function getSsrContext(throwWithoutSsrContext = true) {
52
+ const {
53
+ ssrContext
54
+ } = getGlobalState();
55
+ if (!ssrContext && throwWithoutSsrContext) {
56
+ throw new Error('No SSR context found');
57
+ }
58
+ return ssrContext;
59
+ }
60
+ /**
61
+ * Provides global state to its children.
62
+ * @param prop.children Component children, which will be provided with
63
+ * the global state, and rendered in place of the provider.
64
+ * @param prop.initialState Initial content of the global state.
65
+ * @param prop.ssrContext Server-side rendering (SSR) context.
66
+ * @param prop.stateProxy This option is useful for code
67
+ * splitting and SSR implementation:
68
+ * - If `true`, this provider instance will fetch and reuse the global state
69
+ * from a parent provider.
70
+ * - If `GlobalState` instance, it will be used by this provider.
71
+ * - If not given, a new `GlobalState` instance will be created and used.
72
+ */
73
+ function GlobalStateProvider({
74
+ children,
75
+ ...rest
76
+ }) {
77
+ const state = (0, _react.useRef)();
78
+ if (!state.current) {
79
+ // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
80
+ // graceful compatibility with JavaScript - if "undefined" stateProxy value
81
+ // is given, we want to follow the second branch, which creates a new
82
+ // GlobalState with whatever intiialState given.
83
+ if ('stateProxy' in rest && rest.stateProxy) {
84
+ if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
85
+ } else {
86
+ const {
87
+ initialState,
88
+ ssrContext
89
+ } = rest;
90
+ state.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
91
+ }
92
+ }
93
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(context.Provider, {
94
+ value: state.current,
95
+ children: children
96
+ });
97
+ }
98
+ GlobalStateProvider.defaultProps = {
99
+ children: undefined
100
+ };
101
+ //# sourceMappingURL=GlobalStateProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","context","createContext","getGlobalState","globalState","useContext","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","state","useRef","current","stateProxy","initialState","GlobalState","isFunction","jsx","Provider","value","defaultProps","undefined"],"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":";;;;;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAXxC;;AAgBA,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,iBAAU,EAACJ,OAAO,CAAC;EACvC;EACA,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACM,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,mBAAmBA,CAIzC;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,EACpE;EACA,MAAMC,KAAK,GAAG,IAAAC,aAAM,EAAmC,CAAC;EACxD,IAAI,CAACD,KAAK,CAACE,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIH,IAAI,IAAIA,IAAI,CAACI,UAAU,EAAE;MAC3C,IAAIJ,IAAI,CAACI,UAAU,KAAK,IAAI,EAAEH,KAAK,CAACE,OAAO,GAAGZ,cAAc,CAAC,CAAC,CAAC,KAC1DU,KAAK,CAACE,OAAO,GAAGH,IAAI,CAACI,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGG,IAA0C;MAE/EC,KAAK,CAACE,OAAO,GAAG,IAAIG,oBAAW,CAC7B,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACE,IAAAT,WAAA,CAAAoB,GAAA,EAACnB,OAAO,CAACoB,QAAQ;IAACC,KAAK,EAAET,KAAK,CAACE,OAAQ;IAAAJ,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAD,mBAAmB,CAACa,YAAY,GAAG;EACjCZ,QAAQ,EAAEa;AACZ,CAAC"}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ class SsrContext {
8
+ dirty = false;
9
+ pending = [];
10
+ constructor(state) {
11
+ this.state = state;
12
+ }
13
+ }
14
+ exports.default = SsrContext;
15
+ //# sourceMappingURL=SsrContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SsrContext.js","names":["SsrContext","dirty","pending","constructor","state","exports","default"],"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":";;;;;;AAAe,MAAMA,UAAU,CAAS;EACtCC,KAAK,GAAY,KAAK;EAEtBC,OAAO,GAAoB,EAAE;EAI7BC,WAAWA,CAACC,KAAc,EAAE;IAC1B,IAAI,CAACA,KAAK,GAAGA,KAAK;EACpB;AACF;AAACC,OAAA,CAAAC,OAAA,GAAAN,UAAA"}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ Object.defineProperty(exports, "GlobalState", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _GlobalState.default;
11
+ }
12
+ });
13
+ Object.defineProperty(exports, "GlobalStateProvider", {
14
+ enumerable: true,
15
+ get: function () {
16
+ return _GlobalStateProvider.default;
17
+ }
18
+ });
19
+ Object.defineProperty(exports, "SsrContext", {
20
+ enumerable: true,
21
+ get: function () {
22
+ return _SsrContext.default;
23
+ }
24
+ });
25
+ Object.defineProperty(exports, "getGlobalState", {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _GlobalStateProvider.getGlobalState;
29
+ }
30
+ });
31
+ Object.defineProperty(exports, "getSsrContext", {
32
+ enumerable: true,
33
+ get: function () {
34
+ return _GlobalStateProvider.getSsrContext;
35
+ }
36
+ });
37
+ Object.defineProperty(exports, "newAsyncDataEnvelope", {
38
+ enumerable: true,
39
+ get: function () {
40
+ return _useAsyncData.newAsyncDataEnvelope;
41
+ }
42
+ });
43
+ Object.defineProperty(exports, "useAsyncCollection", {
44
+ enumerable: true,
45
+ get: function () {
46
+ return _useAsyncCollection.default;
47
+ }
48
+ });
49
+ Object.defineProperty(exports, "useAsyncData", {
50
+ enumerable: true,
51
+ get: function () {
52
+ return _useAsyncData.default;
53
+ }
54
+ });
55
+ Object.defineProperty(exports, "useGlobalState", {
56
+ enumerable: true,
57
+ get: function () {
58
+ return _useGlobalState.default;
59
+ }
60
+ });
61
+ Object.defineProperty(exports, "withGlobalStateType", {
62
+ enumerable: true,
63
+ get: function () {
64
+ return _withGlobalStateType.default;
65
+ }
66
+ });
67
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
68
+ var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
69
+ var _SsrContext = _interopRequireDefault(require("./SsrContext"));
70
+ var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
71
+ var _useAsyncData = _interopRequireWildcard(require("./useAsyncData"));
72
+ var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
73
+ var _withGlobalStateType = _interopRequireDefault(require("./withGlobalStateType"));
74
+ 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); }
75
+ 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 && Object.prototype.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; }
76
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_withGlobalStateType","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set"],"sources":["../../src/index.ts"],"sourcesContent":["export { default as GlobalState } from './GlobalState';\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as SsrContext } from './SsrContext';\n\nexport {\n type AsyncCollectionLoaderT,\n default as useAsyncCollection,\n} from './useAsyncCollection';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n default as useAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nexport {\n type SetterT,\n type UseGlobalStateResT,\n default as useGlobalState,\n} from './useGlobalState';\n\nexport { type ForceT, type ValueOrInitializerT } from './utils';\n\nexport { default as withGlobalStateType } from './withGlobalStateType';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAMA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAH,uBAAA,CAAAF,OAAA;AASA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAQA,IAAAO,oBAAA,GAAAR,sBAAA,CAAAC,OAAA;AAAuE,SAAAQ,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAP,wBAAAO,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAjB,CAAA,EAAAc,CAAA,SAAAI,CAAA,GAAAR,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAI,CAAA,KAAAA,CAAA,CAAAX,GAAA,IAAAW,CAAA,CAAAC,GAAA,IAAAR,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAI,CAAA,IAAAV,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAgB,GAAA,CAAAnB,CAAA,EAAAQ,CAAA,GAAAA,CAAA"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
9
+ /**
10
+ * Loads and uses an item in an async collection.
11
+ */
12
+
13
+ /**
14
+ * Resolves and stores at the given `path` of global state elements of
15
+ * an asynchronous data collection. In other words, it is an auxiliar wrapper
16
+ * around {@link useAsyncData}, which uses a loader which resolves to different
17
+ * data, based on ID argument passed in, and stores data fetched for different
18
+ * IDs in the state.
19
+ * @param id ID of the collection item to load & use.
20
+ * @param path The global state path where entire collection should be
21
+ * stored.
22
+ * @param loader A loader function, which takes an
23
+ * ID of data to load, and resolves to the corresponding data.
24
+ * @param options Additional options.
25
+ * @param options.deps An array of dependencies, which trigger
26
+ * data reload when changed. Given dependency changes are watched shallowly
27
+ * (similarly to the standard React's
28
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
29
+ * @param options.noSSR If `true`, this hook won't load data during
30
+ * server-side rendering.
31
+ * @param options.garbageCollectAge The maximum age of data
32
+ * (in milliseconds), after which they are dropped from the state when the last
33
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
34
+ * `maxage` option value.
35
+ * @param options.maxage The maximum age of
36
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
37
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
38
+ * @param options.refreshAge The maximum age of data
39
+ * (in milliseconds), after which their refreshment will be triggered when
40
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
41
+ * Defaults to `maxage` value.
42
+ * @return Returns an object with three fields: `data` holds the actual result of
43
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
44
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
45
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
46
+ * is Unix timestamp of related data currently loaded into the global state.
47
+ *
48
+ * Note that loaded data, if any, are stored at the given `path` of global state
49
+ * along with related meta-information, using slightly different state segment
50
+ * structure (see {@link AsyncDataEnvelope}). That segment of the global state
51
+ * can be accessed, and even modified using other hooks,
52
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
53
+ * `useAsyncData()` hooks logic.
54
+ */
55
+
56
+ function useAsyncCollection(id, path, loader, options = {}) {
57
+ const itemPath = path ? `${path}.${id}` : id;
58
+ return (0, _useAsyncData.default)(itemPath, oldData => loader(id, oldData), options);
59
+ }
60
+ var _default = exports.default = useAsyncCollection;
61
+ //# sourceMappingURL=useAsyncCollection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_useAsyncData","_interopRequireDefault","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 useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, 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 | false = false,\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"],"mappings":";;;;;;;AAIA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AAJA;AACA;AACA;;AAaA;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,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;EACzB,MAAMC,QAAQ,GAAGH,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAO,IAAAK,qBAAY,EACjBD,QAAQ,EACPE,OAAqB,IAAKJ,MAAM,CAACF,EAAE,EAAEM,OAAO,CAAC,EAC9CH,OACF,CAAC;AACH;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,kBAAkB"}
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
9
+ var _lodash = require("lodash");
10
+ var _react = require("react");
11
+ var _uuid = require("uuid");
12
+ var _jsUtils = require("@dr.pogodin/js-utils");
13
+ var _GlobalStateProvider = require("./GlobalStateProvider");
14
+ var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
15
+ var _utils = require("./utils");
16
+ /**
17
+ * Loads and uses async data into the GlobalState path.
18
+ */
19
+
20
+ const DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
21
+
22
+ function newAsyncDataEnvelope(initialData = null) {
23
+ return {
24
+ data: initialData,
25
+ numRefs: 0,
26
+ operationId: '',
27
+ timestamp: 0
28
+ };
29
+ }
30
+ /**
31
+ * Executes the data loading operation.
32
+ * @param path Data segment path inside the global state.
33
+ * @param loader Data loader.
34
+ * @param globalState The global state instance.
35
+ * @param oldData Optional. Previously fetched data, currently stored in
36
+ * the state, if already fetched by the caller; otherwise, they will be fetched
37
+ * by the load() function itself.
38
+ * @param opIdPrefix operationId prefix to use, which should be
39
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
40
+ * context).
41
+ * @return Resolves once the operation is done.
42
+ * @ignore
43
+ */
44
+ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
45
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
46
+ /* eslint-disable no-console */
47
+ console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
48
+ /* eslint-enable no-console */
49
+ }
50
+
51
+ const operationId = opIdPrefix + (0, _uuid.v4)();
52
+ const operationIdPath = path ? `${path}.operationId` : 'operationId';
53
+ globalState.set(operationIdPath, operationId);
54
+ const data = await loader(oldData || globalState.get(path).data);
55
+ const state = globalState.get(path);
56
+ if (operationId === state.operationId) {
57
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
58
+ /* eslint-disable no-console */
59
+ console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
60
+ console.log('Data:', (0, _lodash.cloneDeep)(data));
61
+ /* eslint-enable no-console */
62
+ }
63
+
64
+ globalState.set(path, {
65
+ ...state,
66
+ data,
67
+ operationId: '',
68
+ timestamp: Date.now()
69
+ });
70
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
71
+ /* eslint-disable no-console */
72
+ console.groupEnd();
73
+ /* eslint-enable no-console */
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Resolves asynchronous data, and stores them at given `path` of global
80
+ * state. When multiple components rely on asynchronous data at the same `path`,
81
+ * the data are resolved once, and reused until their age is within specified
82
+ * bounds. Once the data are stale, the hook allows to refresh them. It also
83
+ * garbage-collects stale data from the global state when the last component
84
+ * relying on them is unmounted.
85
+ * @param path Dot-delimitered state path, where data envelop is
86
+ * stored.
87
+ * @param loader Asynchronous function which resolves (loads)
88
+ * data, which should be stored at the global state `path`. When multiple
89
+ * components
90
+ * use `useAsyncData()` hook for the same `path`, the library assumes that all
91
+ * hook instances are called with the same `loader` (_i.e._ whichever of these
92
+ * loaders is used to resolve async data, the result is acceptable to be reused
93
+ * in all related components).
94
+ * @param options Additional options.
95
+ * @param options.deps An array of dependencies, which trigger
96
+ * data reload when changed. Given dependency changes are watched shallowly
97
+ * (similarly to the standard React's
98
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
99
+ * @param options.noSSR If `true`, this hook won't load data during
100
+ * server-side rendering.
101
+ * @param options.garbageCollectAge The maximum age of data
102
+ * (in milliseconds), after which they are dropped from the state when the last
103
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
104
+ * `maxage` option value.
105
+ * @param options.maxage The maximum age of
106
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
107
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
108
+ * @param options.refreshAge The maximum age of data
109
+ * (in milliseconds), after which their refreshment will be triggered when
110
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
111
+ * Defaults to `maxage` value.
112
+ * @return Returns an object with three fields: `data` holds the actual result of
113
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
114
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
115
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
116
+ * is Unix timestamp of related data currently loaded into the global state.
117
+ *
118
+ * Note that loaded data, if any, are stored at the given `path` of global state
119
+ * along with related meta-information, using slightly different state segment
120
+ * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
121
+ * can be accessed, and even modified using other hooks,
122
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
123
+ * `useAsyncData()` hooks logic.
124
+ */
125
+
126
+ function useAsyncData(path, loader, options = {}) {
127
+ const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
128
+ const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
129
+ const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
130
+
131
+ // Note: here we can't depend on useGlobalState() to init the initial value,
132
+ // because that way we'll have issues with SSR (see details below).
133
+ const globalState = (0, _GlobalStateProvider.getGlobalState)();
134
+ const state = globalState.get(path, {
135
+ initialValue: newAsyncDataEnvelope()
136
+ });
137
+ if (globalState.ssrContext && !options.noSSR) {
138
+ if (!state.timestamp && !state.operationId) {
139
+ globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
140
+ }
141
+ } else {
142
+ // This takes care about the client-side reference counting, and garbage
143
+ // collection.
144
+ //
145
+ // Note: the Rules of Hook below are violated by conditional call to a hook,
146
+ // but as the condition is actually server-side or client-side environment,
147
+ // it is effectively non-conditional at the runtime.
148
+ //
149
+ // TODO: Though, maybe there is a way to refactor it into a cleaner code.
150
+ // The same applies to other useEffect() hooks below.
151
+ (0, _react.useEffect)(() => {
152
+ // eslint-disable-line react-hooks/rules-of-hooks
153
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
154
+ const numRefs = globalState.get(numRefsPath);
155
+ globalState.set(numRefsPath, numRefs + 1);
156
+ return () => {
157
+ const state2 = globalState.get(path);
158
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
159
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
160
+ /* eslint-disable no-console */
161
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
162
+ /* eslint-enable no-console */
163
+ }
164
+
165
+ globalState.set(path, {
166
+ ...state2,
167
+ data: null,
168
+ numRefs: 0,
169
+ timestamp: 0
170
+ });
171
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
172
+ };
173
+ }, [garbageCollectAge, globalState, path]);
174
+
175
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
176
+ // special case the otherwise wrong behavior is actually what we need.
177
+
178
+ // Data loading and refreshing.
179
+ let loadTriggered = false;
180
+ (0, _react.useEffect)(() => {
181
+ // eslint-disable-line react-hooks/rules-of-hooks
182
+ const state2 = globalState.get(path);
183
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
184
+ load(path, loader, globalState, state2.data);
185
+ loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
186
+ }
187
+ });
188
+
189
+ const deps = options.deps || [];
190
+ (0, _react.useEffect)(() => {
191
+ // eslint-disable-line react-hooks/rules-of-hooks
192
+ if (!loadTriggered && deps.length) load(path, loader, globalState, null);
193
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
194
+ }
195
+
196
+ const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
197
+ return {
198
+ data: maxage < Date.now() - localState.timestamp ? null : localState.data,
199
+ loading: Boolean(localState.operationId),
200
+ timestamp: localState.timestamp
201
+ };
202
+ }
203
+ var _default = exports.default = useAsyncData;
204
+ //# sourceMappingURL=useAsyncData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","data","numRefs","operationId","timestamp","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","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean","_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 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 | false = false,\n DataT = unknown,\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"],"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;;AAqBA,MAAMQ,cAAc,GAAG,CAAC,GAAGC,eAAM,CAAC,CAAC;;AAY5B,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EACL;EAC3B,OAAO;IACLC,IAAI,EAAED,WAAW;IACjBE,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,EACrBC,UAAqB,GAAG,GAAG,EACZ;EACf,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;IAC1D;IACAC,OAAO,CAACC,GAAG,CACR,4DAA2DV,IAAI,IAAI,EAAG,GACzE,CAAC;IACD;EACF;;EACA,MAAMH,WAAW,GAAGO,UAAU,GAAG,IAAAO,QAAI,EAAC,CAAC;EACvC,MAAMC,eAAe,GAAGZ,IAAI,GAAI,GAAEA,IAAK,cAAa,GAAG,aAAa;EACpEE,WAAW,CAACW,GAAG,CAAiBD,eAAe,EAAEf,WAAW,CAAC;EAC7D,MAAMF,IAAI,GAAG,MAAMM,MAAM,CACvBE,OAAO,IAAKD,WAAW,CAACY,GAAG,CAAoCd,IAAI,CAAC,CAAEL,IACx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EACjCzC,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLE,IAAI,EAAE4B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGqB,UAAU,CAAC1C,SAAS,GAAG,IAAI,GAAG0C,UAAU,CAAC7C,IAAI;IACzE+C,OAAO,EAAEC,OAAO,CAACH,UAAU,CAAC3C,WAAW,CAAC;IACxCC,SAAS,EAAE0C,UAAU,CAAC1C;EACxB,CAAC;AACH;AAAC,IAAA8C,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEczB,YAAY"}
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _lodash = require("lodash");
8
+ var _react = require("react");
9
+ var _jsUtils = require("@dr.pogodin/js-utils");
10
+ var _GlobalStateProvider = require("./GlobalStateProvider");
11
+ var _utils = require("./utils");
12
+ // Hook for updates of global state.
13
+
14
+ /**
15
+ * The primary hook for interacting with the global state, modeled after
16
+ * the standard React's
17
+ * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
18
+ * It subscribes a component to a given `path` of global state, and provides
19
+ * a function to update it. Each time the value at `path` changes, the hook
20
+ * triggers re-render of its host component.
21
+ *
22
+ * **Note:**
23
+ * - For performance, the library does not copy objects written to / read from
24
+ * global state paths. You MUST NOT manually mutate returned state values,
25
+ * or change objects already written into the global state, without explicitly
26
+ * clonning them first yourself.
27
+ * - State update notifications are asynchronous. When your code does multiple
28
+ * global state updates in the same React rendering cycle, all state update
29
+ * notifications are queued and dispatched together, after the current
30
+ * rendering cycle. In other words, in any given rendering cycle the global
31
+ * state values are "fixed", and all changes becomes visible at once in the
32
+ * next triggered rendering pass.
33
+ *
34
+ * @param path Dot-delimitered state path. It can be undefined to
35
+ * subscribe for entire state.
36
+ *
37
+ * Under-the-hood state values are read and written using `lodash`
38
+ * [_.get()](https://lodash.com/docs/4.17.15#get) and
39
+ * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
40
+ * to access state paths which have not been created before.
41
+ * @param initialValue Initial value to set at the `path`, or its
42
+ * factory:
43
+ * - If a function is given, it will act similar to
44
+ * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
45
+ * only if the value at `path` is `undefined`, the function will be executed,
46
+ * and the value it returns will be written to the `path`.
47
+ * - Otherwise, the given value itself will be written to the `path`,
48
+ * if the current value at `path` is `undefined`.
49
+ * @return It returs an array with two elements: `[value, setValue]`:
50
+ *
51
+ * - The `value` is the current value at given `path`.
52
+ *
53
+ * - The `setValue()` is setter function to write a new value to the `path`.
54
+ *
55
+ * Similar to the standard React's `useState()`, it supports
56
+ * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
57
+ * if `setValue()` is called with a function as argument, that function will
58
+ * be called and its return value will be written to `path`. Otherwise,
59
+ * the argument of `setValue()` itself is written to `path`.
60
+ *
61
+ * Also, similar to the standard React's state setters, `setValue()` is
62
+ * stable function: it does not change between component re-renders.
63
+ */
64
+
65
+ function useGlobalState(path, initialValue) {
66
+ const globalState = (0, _GlobalStateProvider.getGlobalState)();
67
+ const ref = (0, _react.useRef)();
68
+ const rc = ref.current || {
69
+ emitter: new _jsUtils.Emitter(),
70
+ globalState,
71
+ path,
72
+ setter: value => {
73
+ const newState = (0, _lodash.isFunction)(value) ? value(rc.state) : value;
74
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
75
+ /* eslint-disable no-console */
76
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
77
+ console.log('New value:', (0, _lodash.cloneDeep)(newState));
78
+ console.groupEnd();
79
+ /* eslint-enable no-console */
80
+ }
81
+
82
+ rc.globalState.set(rc.path, newState);
83
+ },
84
+ state: (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue,
85
+ watcher: () => {
86
+ const state = rc.globalState.get(rc.path);
87
+ if (state !== rc.state) rc.emitter.emit();
88
+ }
89
+ };
90
+ ref.current = rc;
91
+ rc.globalState = globalState;
92
+ rc.path = path;
93
+ rc.state = (0, _react.useSyncExternalStore)(cb => rc.emitter.addListener(cb), () => rc.globalState.get(rc.path, {
94
+ initialValue
95
+ }), () => rc.globalState.get(rc.path, {
96
+ initialValue,
97
+ initialState: true
98
+ }));
99
+ (0, _react.useEffect)(() => {
100
+ const {
101
+ watcher
102
+ } = ref.current;
103
+ globalState.watch(watcher);
104
+ watcher();
105
+ return () => globalState.unWatch(watcher);
106
+ }, [globalState]);
107
+ (0, _react.useEffect)(() => {
108
+ ref.current.watcher();
109
+ }, [path]);
110
+ return [rc.state, rc.setter];
111
+ }
112
+ var _default = exports.default = useGlobalState;
113
+ //# sourceMappingURL=useGlobalState.js.map