@dr.pogodin/react-global-state 0.19.3 → 0.20.0

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.
@@ -71,22 +71,25 @@ const GlobalStateProvider = ({
71
71
  children,
72
72
  ...rest
73
73
  }) => {
74
- const localStateRef = (0, _react.useRef)(undefined);
74
+ const [localState, setLocalState] = (0, _react.useState)();
75
75
  let state;
76
- // TODO: Revise.
77
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
76
+
77
+ // Below we cast `rest.stateProxy` as "boolean" for safe backward
78
+ // compatibility with plain JavaScript (as TypeScript typings only
79
+ // permit "true" or GlobalState value; while legacy codebase may
80
+ // pass in a boolean value here, occasionally equal "false").
78
81
  if ('stateProxy' in rest && rest.stateProxy) {
79
- localStateRef.current = undefined;
82
+ if (localState) setLocalState(undefined);
80
83
  state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
84
+ } else if (localState) {
85
+ state = localState;
81
86
  } else {
82
- if (!localStateRef.current) {
83
- const {
84
- initialState,
85
- ssrContext
86
- } = rest;
87
- localStateRef.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
88
- }
89
- state = localStateRef.current;
87
+ const {
88
+ initialState,
89
+ ssrContext
90
+ } = rest;
91
+ state = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
92
+ setLocalState(state);
90
93
  }
91
94
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(Context, {
92
95
  value: state,
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","Context","createContext","getGlobalState","globalState","use","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localStateRef","useRef","undefined","state","stateProxy","current","initialState","GlobalState","isFunction","jsx","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type 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 // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\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 */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n const localStateRef = useRef<GST>(undefined);\n let state: GST;\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ('stateProxy' in rest && rest.stateProxy) {\n localStateRef.current = undefined;\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else {\n if (!localStateRef.current) {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n localStateRef.current = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n state = localStateRef.current;\n }\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;E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ACA,oBAAO,IAAAlB,WAAA,CAAAsB,GAAA,EAACrB,OAAO;IAACsB,KAAK,EAAEP,KAAM;IAAAL,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAAC,IAAAa,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEahB,mBAAmB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","Context","createContext","getGlobalState","globalState","use","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localState","setLocalState","useState","state","stateProxy","undefined","initialState","GlobalState","isFunction","jsx","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type 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 // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\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 */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,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,UAAG,EAACJ,OAAO,CAAC;EAChC,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;AACA,MAAMC,mBAAmB,GAAGA,CAI1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KACtD;EAGd,MAAM,CAACC,UAAU,EAAEC,aAAa,CAAC,GAAG,IAAAC,eAAQ,EAAM,CAAC;EAEnD,IAAIC,KAAU;;EAEd;EACA;EACA;EACA;EACA,IAAI,YAAY,IAAIJ,IAAI,IAAKA,IAAI,CAACK,UAAsB,EAAE;IACxD,IAAIJ,UAAU,EAAEC,aAAa,CAACI,SAAS,CAAC;IACxCF,KAAK,GAAGJ,IAAI,CAACK,UAAU,KAAK,IAAI,GAAGd,cAAc,CAAC,CAAC,GAAGS,IAAI,CAACK,UAAU;EACvE,CAAC,MAAM,IAAIJ,UAAU,EAAE;IACrBG,KAAK,GAAGH,UAAU;EACpB,CAAC,MAAM;IACL,MAAM;MACJM,YAAY;MACZV;IACF,CAAC,GAAGG,IAA0C;IAE9CI,KAAK,GAAG,IAAII,oBAAW,CACrB,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDV,UACF,CAAC;IAEDK,aAAa,CAACE,KAAK,CAAC;EACtB;EAEA,oBAAO,IAAAhB,WAAA,CAAAsB,GAAA,EAACrB,OAAO;IAACsB,KAAK,EAAEP,KAAM;IAAAL,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAAC,IAAAa,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEahB,mBAAmB","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","api","GlobalState","GlobalStateProvider","SsrContext","getGlobalState","getSsrContext","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n SsrContext: typeof SsrContext<StateT>;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAL,OAAA;AAWA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAAwE,SAAAE,wBAAAK,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAP,uBAAA,YAAAA,CAAAK,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,UAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,GAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,EAAAQ,CAAA,gBAAAP,CAAA,IAAAD,CAAA,gBAAAC,CAAA,OAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,EAAAC,CAAA,OAAAM,CAAA,IAAAD,CAAA,GAAAU,MAAA,CAAAC,cAAA,KAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,EAAAC,CAAA,OAAAM,CAAA,CAAAK,GAAA,IAAAL,CAAA,CAAAM,GAAA,IAAAP,CAAA,CAAAE,CAAA,EAAAP,CAAA,EAAAM,CAAA,IAAAC,CAAA,CAAAP,CAAA,IAAAD,CAAA,CAAAC,CAAA,WAAAO,CAAA,KAAAR,CAAA,EAAAC,CAAA;AA0BxE;;AAgBA,MAAMkB,GAAG,GAAG;EACV;EACA;EACA;EACAC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,UAAU,EAAVA,mBAAU;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,oBAAoB,EAApBA,kCAAoB;EACpBC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAGL;EAC5B,OAAOV,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","api","GlobalState","GlobalStateProvider","SsrContext","getGlobalState","getSsrContext","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n SsrContext: typeof SsrContext<StateT>;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";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D,CAAA,CAAAC,CAAA,WAAAO,CAAA,KAAAR,CAAA,EAAAC,CAAA;AA8BxE;;AAgBA,MAAMkB,GAAG,GAAG;EACV;EACA;EACA;EACAC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,UAAU,EAAVA,mBAAU;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,oBAAoB,EAApBA,kCAAoB;EACpBC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAGL;EAC5B,OAAOV,GAAG;AACZ","ignoreList":[]}
@@ -89,68 +89,6 @@ function normalizeIds(idOrIds) {
89
89
  return [idOrIds];
90
90
  }
91
91
 
92
- /**
93
- * Inits/updates, and returns the heap.
94
- */
95
- function useHeap(ids, path, loader, gs) {
96
- const ref = (0, _react.useRef)(undefined);
97
- let heap = ref.current;
98
- if (heap) {
99
- // Update.
100
- heap.ids = ids;
101
- heap.path = path;
102
- heap.loader = loader;
103
- heap.globalState = gs;
104
- } else {
105
- // Initialization.
106
- const reload = async customLoader => {
107
- const heap2 = ref.current;
108
- const localLoader = customLoader ?? heap2.loader;
109
- // TODO: Revise - not sure all related typing is 100% correct,
110
- // thus let's keep this runtime assertion.
111
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
112
- if (!localLoader || !heap2.globalState || !heap2.ids) {
113
- throw Error('Internal error');
114
- }
115
- for (const id of heap2.ids) {
116
- const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
117
- const promiseOrVoid = (0, _useAsyncData.load)(itemPath,
118
- // TODO: Revise! Most probably we don't have fully correct loader
119
- // typing, as it may return either promise or value, and those two
120
- // cases call for different runtime behavior, which in turns only
121
- // happens if the outer function on the next line matches the same
122
- // async / sync signature.
123
- // eslint-disable-next-line @typescript-eslint/promise-function-async
124
- (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
125
- if (promiseOrVoid instanceof Promise) await promiseOrVoid;
126
- }
127
- };
128
- heap = {
129
- globalState: gs,
130
- ids,
131
- loader,
132
- path,
133
- reload,
134
- // TODO: Revise! Most probably we don't have fully correct loader
135
- // typing, as it may return either promise or value, and those two
136
- // cases call for different runtime behavior, which in turns only
137
- // happens if the outer function on the next line matches the same
138
- // async / sync signature.
139
- // eslint-disable-next-line @typescript-eslint/promise-function-async
140
- reloadSingle: customLoader => ref.current.reload(
141
- // TODO: Revise! Most probably we don't have fully correct loader
142
- // typing, as it may return either promise or value, and those two
143
- // cases call for different runtime behavior, which in turns only
144
- // happens if the outer function on the next line matches the same
145
- // async / sync signature.
146
- // eslint-disable-next-line @typescript-eslint/promise-function-async
147
- customLoader && ((id, ...args) => customLoader(...args)))
148
- };
149
- ref.current = heap;
150
- }
151
- return heap;
152
- }
153
-
154
92
  /**
155
93
  * Resolves and stores at the given `path` of the global state elements of
156
94
  * an asynchronous data collection.
@@ -166,7 +104,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
166
104
  const refreshAge = options.refreshAge ?? maxage;
167
105
  const garbageCollectAge = options.garbageCollectAge ?? maxage;
168
106
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
169
- const heap = useHeap(ids, path, loader, globalState);
170
107
 
171
108
  // Server-side logic.
172
109
  if (globalState.ssrContext) {
@@ -245,6 +182,70 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
245
182
  });
246
183
  }
247
184
  const [localState] = (0, _useGlobalState.default)(path, {});
185
+ const ref = (0, _react.useRef)(null);
186
+ ref.current ??= {
187
+ globalState,
188
+ ids,
189
+ loader,
190
+ path
191
+ };
192
+ (0, _react.useEffect)(() => {
193
+ ref.current = {
194
+ globalState,
195
+ ids,
196
+ loader,
197
+ path
198
+ };
199
+ }, [globalState, ids, loader, path]);
200
+ const [stable] = (0, _react.useState)(() => {
201
+ const reload = async customLoader => {
202
+ const rc = ref.current;
203
+ if (!rc) throw Error('Internal error');
204
+ const localLoader = customLoader ?? rc.loader;
205
+
206
+ // TODO: Revise - not sure all related typing is 100% correct,
207
+ // thus let's keep this runtime assertion.
208
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
209
+ if (!localLoader || !rc.globalState || !rc.ids) {
210
+ throw Error('Internal error');
211
+ }
212
+ for (const id of rc.ids) {
213
+ const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;
214
+ const promiseOrVoid = (0, _useAsyncData.load)(itemPath,
215
+ // TODO: Revise! Most probably we don't have fully correct loader
216
+ // typing, as it may return either promise or value, and those two
217
+ // cases call for different runtime behavior, which in turns only
218
+ // happens if the outer function on the next line matches the same
219
+ // async / sync signature.
220
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
221
+ (oldData, meta) => localLoader(id, oldData, meta), rc.globalState);
222
+ if (promiseOrVoid instanceof Promise) await promiseOrVoid;
223
+ }
224
+ };
225
+
226
+ // TODO: Revise! Most probably we don't have fully correct loader
227
+ // typing, as it may return either promise or value, and those two
228
+ // cases call for different runtime behavior, which in turns only
229
+ // happens if the outer function on the next line matches the same
230
+ // async / sync signature.
231
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
232
+ const reloadSingle = customLoader => reload(
233
+ // TODO: Revise! Most probably we don't have fully correct loader
234
+ // typing, as it may return either promise or value, and those two
235
+ // cases call for different runtime behavior, which in turns only
236
+ // happens if the outer function on the next line matches the same
237
+ // async / sync signature.
238
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
239
+ customLoader && ((id, ...args) => customLoader(...args)));
240
+ const setSingle = data => {
241
+ void reload(() => data);
242
+ };
243
+ return {
244
+ reload,
245
+ reloadSingle,
246
+ setSingle
247
+ };
248
+ });
248
249
  if (!Array.isArray(idOrIds)) {
249
250
  // TODO: Revise related typings!
250
251
  const e = localState[idOrIds];
@@ -252,14 +253,15 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
252
253
  return {
253
254
  data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
254
255
  loading: !!e?.operationId,
255
- reload: heap.reloadSingle,
256
+ reload: stable.reloadSingle,
257
+ set: stable.setSingle,
256
258
  timestamp
257
259
  };
258
260
  }
259
261
  const res = {
260
262
  items: {},
261
263
  loading: false,
262
- reload: heap.reload,
264
+ reload: stable.reload,
263
265
  timestamp: Number.MAX_VALUE
264
266
  };
265
267
  for (const id of ids) {
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","load","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","disabled","noSSR","operationId","uuid","state","initialValue","data","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>(undefined);\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader ?? heap2.loader;\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (const id of heap2.ids) {\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n const promiseOrVoid = load(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n heap = {\n globalState: gs,\n ids,\n loader,\n path,\n reload,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n reloadSingle: (customLoader) => ref.current!.reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n ),\n };\n ref.current = heap;\n }\n\n return heap;\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | null> => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n\n // Client-side logic.\n } else {\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await load(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: heap.reloadSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT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AAkB,EAEjC","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","globalState","getGlobalState","ssrContext","disabled","noSSR","operationId","uuid","itemPath","state","initialValue","promiseOrVoid","load","args","data","Promise","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","ref","useRef","current","stable","useState","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | null> => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n\n // Client-side logic.\n } else {\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await load(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = load(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAGA,IAAAE,oBAAA,GAAAF,OAAA;AAEA,IAAAG,aAAA,GAAAH,OAAA;AAYA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAxBA;AACA;AACA;;AA8EA;AACA;AACA;AACA;AACA;AACA;AACA,SAASO,YAAYA,CACnBC,GAAU,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AEF,MAAM,CAACS,YAAY;MAC3B9E,GAAG,EAAEqE,MAAM,CAACU,SAAS;MACrBhE;IACF,CAAC;EACH;EAEA,MAAMb,GAAuC,GAAG;IAC9CgF,KAAK,EAAE,CAAC,CAAwC;IAChDD,OAAO,EAAE,KAAK;IACdV,MAAM,EAAEF,MAAM,CAACE,MAAM;IACrBxD,SAAS,EAAEoE,MAAM,CAACC;EACpB,CAAC;EAED,KAAK,MAAMxF,EAAE,IAAIL,GAAG,EAAE;IACpB;IACA,MAAMyF,CAAC,GAAGhB,UAAU,CAACpE,EAAE,CAAW;IAClC,MAAMqF,OAAO,GAAG,CAAC,CAACD,CAAC,EAAErC,WAAW;IAChC,MAAM5B,SAAS,GAAGiE,CAAC,EAAEjE,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACgF,KAAK,CAACtF,EAAE,CAAC,GAAG;MACduD,IAAI,EAAEjB,MAAM,GAAGvB,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAGiE,CAAC,EAAE7B,IAAI,IAAI,IAAI;MAC9D8B,OAAO;MACPlE;IACF,CAAC;IACDb,GAAG,CAAC+E,OAAO,KAAKA,OAAO;IACvB,IAAI/E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAAmF,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcxD,kBAAkB,EAEjC","ignoreList":[]}
@@ -39,7 +39,30 @@ function newAsyncDataEnvelope(initialData = null, {
39
39
  timestamp
40
40
  };
41
41
  }
42
- function finalizeLoad(data, path, globalState, operationId) {
42
+ /**
43
+ * Writes data into the global state, and prints console messages in the debug
44
+ * mode.
45
+ */
46
+ function setState(data, path, gs, prevState = gs.get(path)) {
47
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
+ /* eslint-disable no-console */
49
+ console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
50
+ console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
51
+ /* eslint-enable no-console */
52
+ }
53
+ gs.set(path, {
54
+ ...prevState,
55
+ data,
56
+ operationId: '',
57
+ timestamp: Date.now()
58
+ });
59
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
60
+ /* eslint-disable no-console */
61
+ console.groupEnd();
62
+ /* eslint-enable no-console */
63
+ }
64
+ }
65
+ function finalizeLoad(data, path, gs, operationId) {
43
66
  // NOTE: We don't really mean that it hasn't been aborted,
44
67
  // the "false" flag rather says we don't need to trigger "on aborted"
45
68
  // callback for this operation, if any is registered - just drop it.
@@ -47,27 +70,9 @@ function finalizeLoad(data, path, globalState, operationId) {
47
70
  // Also, in the synchronous state update mode, we don't really need to set up
48
71
  // the abort callback at all (as there is no way to use it), but for now it is
49
72
  // set up, thus it should be cleaned out here.
50
- globalState.asyncDataLoadDone(operationId, false);
51
- const state = globalState.get(path);
52
- if (operationId === state?.operationId) {
53
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
54
- /* eslint-disable no-console */
55
- console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
56
- console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
57
- /* eslint-enable no-console */
58
- }
59
- globalState.set(path, {
60
- ...state,
61
- data,
62
- operationId: '',
63
- timestamp: Date.now()
64
- });
65
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
66
- /* eslint-disable no-console */
67
- console.groupEnd();
68
- /* eslint-enable no-console */
69
- }
70
- }
73
+ gs.asyncDataLoadDone(operationId, false);
74
+ const state = gs.get(path);
75
+ if (operationId === state?.operationId) setState(data, path, gs, state);
71
76
  }
72
77
 
73
78
  /**
@@ -144,6 +149,9 @@ operationId = `C${(0, _uuid.v4)()}`) {
144
149
  * state.
145
150
  */
146
151
 
152
+ // TODO: Perhaps split the heap management to a dedicated hook,
153
+ // as it is done inside useAsyncCollection().
154
+
147
155
  function useAsyncData(path, loader, options = {}) {
148
156
  const maxage = options.maxage ?? DEFAULT_MAXAGE;
149
157
  const refreshAge = options.refreshAge ?? maxage;
@@ -166,6 +174,10 @@ function useAsyncData(path, loader, options = {}) {
166
174
  if (!localLoader || !heap.globalState) throw Error('Internal error');
167
175
  return load(heap.path, localLoader, heap.globalState);
168
176
  };
177
+ heap.set ??= data => {
178
+ if (!heap.globalState) throw Error('Internal error');
179
+ setState(data, heap.path, heap.globalState);
180
+ };
169
181
  if (globalState.ssrContext) {
170
182
  if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
171
183
  const promiseOrVoid = load(path, loader, globalState, {
@@ -252,6 +264,7 @@ function useAsyncData(path, loader, options = {}) {
252
264
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
253
265
  loading: Boolean(localState.operationId),
254
266
  reload: heap.reload,
267
+ set: heap.set,
255
268
  timestamp: localState.timestamp
256
269
  };
257
270
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","load","loader","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): void | Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\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 if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBO,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAA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ACtC,CAAC8D,MAAM,CAAC5D,WAAW,IAAI4D,MAAM,CAAC5D,WAAW,CAACgE,UAAU,CAAC,GAAG,CAAC,CAC9D,EACD;UACA,IAAI,CAACF,IAAI,EAAE3D,WAAW,CAAC0D,gBAAgB,CAAC3D,IAAI,IAAI,EAAE,CAAC;UACnD,KAAKiB,IAAI,CAACjB,IAAI,EAAEkB,MAAM,EAAEjB,WAAW,EAAE;YACnCJ,IAAI,EAAE6D,MAAM,CAAC7D,IAAI;YACjBD,SAAS,EAAE8D,MAAM,CAAC9D;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAACmE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjChE,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE0C,MAAM,GAAGzB,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGgD,UAAU,CAACnE,SAAS,GAAG,IAAI,GAAGmE,UAAU,CAAClE,IAAI;IACzEoE,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACjE,WAAW,CAAC;IACxCiD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBnD,SAAS,EAAEmE,UAAU,CAACnE;EACxB,CAAC;AACH;;AAIA","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","setState","path","gs","prevState","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","load","loader","globalState","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: string | null | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\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\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): void | Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n set?: (data: DataT | null) => void;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n heap.set ??= (data: DataT | null) => {\n if (!heap.globalState) throw Error('Internal error');\n setState(data, heap.path, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\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 if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n set: heap.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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: AsyncDataL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