@dr.pogodin/react-global-state 0.19.4 → 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.
- package/build/cjs/GlobalStateProvider.js +15 -12
- package/build/cjs/GlobalStateProvider.js.map +1 -1
- package/build/cjs/useAsyncCollection.js +67 -70
- package/build/cjs/useAsyncCollection.js.map +1 -1
- package/build/cjs/useAsyncData.js.map +1 -1
- package/build/cjs/useGlobalState.js +52 -53
- package/build/cjs/useGlobalState.js.map +1 -1
- package/build/code/GlobalStateProvider.js +16 -13
- package/build/code/GlobalStateProvider.js.map +1 -1
- package/build/code/useAsyncCollection.js +69 -72
- package/build/code/useAsyncCollection.js.map +1 -1
- package/build/code/useAsyncData.js.map +1 -1
- package/build/code/useGlobalState.js +55 -55
- package/build/code/useGlobalState.js.map +1 -1
- package/package.json +18 -17
|
@@ -71,22 +71,25 @@ const GlobalStateProvider = ({
|
|
|
71
71
|
children,
|
|
72
72
|
...rest
|
|
73
73
|
}) => {
|
|
74
|
-
const
|
|
74
|
+
const [localState, setLocalState] = (0, _react.useState)();
|
|
75
75
|
let state;
|
|
76
|
-
|
|
77
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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","
|
|
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 <GlobalStateProvider>} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link <GlobalStateProvider>}\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 <GlobalStateProvider>}.\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":[]}
|
|
@@ -89,72 +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
|
-
// TODO: It should be revised it works correctly.
|
|
149
|
-
setSingle(data) {
|
|
150
|
-
void ref.current.reload(() => data);
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
ref.current = heap;
|
|
154
|
-
}
|
|
155
|
-
return heap;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
92
|
/**
|
|
159
93
|
* Resolves and stores at the given `path` of the global state elements of
|
|
160
94
|
* an asynchronous data collection.
|
|
@@ -170,7 +104,6 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
170
104
|
const refreshAge = options.refreshAge ?? maxage;
|
|
171
105
|
const garbageCollectAge = options.garbageCollectAge ?? maxage;
|
|
172
106
|
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
173
|
-
const heap = useHeap(ids, path, loader, globalState);
|
|
174
107
|
|
|
175
108
|
// Server-side logic.
|
|
176
109
|
if (globalState.ssrContext) {
|
|
@@ -249,6 +182,70 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
249
182
|
});
|
|
250
183
|
}
|
|
251
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
|
+
});
|
|
252
249
|
if (!Array.isArray(idOrIds)) {
|
|
253
250
|
// TODO: Revise related typings!
|
|
254
251
|
const e = localState[idOrIds];
|
|
@@ -256,15 +253,15 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
256
253
|
return {
|
|
257
254
|
data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
|
|
258
255
|
loading: !!e?.operationId,
|
|
259
|
-
reload:
|
|
260
|
-
set:
|
|
256
|
+
reload: stable.reloadSingle,
|
|
257
|
+
set: stable.setSingle,
|
|
261
258
|
timestamp
|
|
262
259
|
};
|
|
263
260
|
}
|
|
264
261
|
const res = {
|
|
265
262
|
items: {},
|
|
266
263
|
loading: false,
|
|
267
|
-
reload:
|
|
264
|
+
reload: stable.reload,
|
|
268
265
|
timestamp: Number.MAX_VALUE
|
|
269
266
|
};
|
|
270
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","setSingle","data","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","disabled","noSSR","operationId","uuid","state","initialValue","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> = (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 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 * 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 // TODO: It should be revised it works correctly.\n setSingle(data: DataT | null) {\n void ref.current!.reload(() => data);\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 set: heap.setSingle,\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}`>, 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;;AA+EA;AACA;AACA;AACA;AACA;AACA;AACA,SAASO,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,M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WAAW;MACzBzB,MAAM,EAAEH,IAAI,CAACc,YAAY;MACzBlD,GAAG,EAAEoC,IAAI,CAACgB,SAAS;MACnBrC;IACF,CAAC;EACH;EAEA,MAAMb,GAAuC,GAAG;IAC9CiF,KAAK,EAAE,CAAC,CAAwC;IAChDD,OAAO,EAAE,KAAK;IACd3C,MAAM,EAAEH,IAAI,CAACG,MAAM;IACnBxB,SAAS,EAAEqE,MAAM,CAACC;EACpB,CAAC;EAED,KAAK,MAAMzF,EAAE,IAAIL,GAAG,EAAE;IACpB;IACA,MAAM0F,CAAC,GAAGF,UAAU,CAACnF,EAAE,CAAW;IAClC,MAAMsF,OAAO,GAAG,CAAC,CAACD,CAAC,EAAEjB,WAAW;IAChC,MAAMjD,SAAS,GAAGkE,CAAC,EAAElE,SAAS,IAAI,CAAC;IAEnCb,GAAG,CAACiF,KAAK,CAACvF,EAAE,CAAC,GAAG;MACdyD,IAAI,EAAEG,MAAM,GAAG7C,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,GAAGkE,CAAC,EAAE5B,IAAI,IAAI,IAAI;MAC9D6B,OAAO;MACPnE;IACF,CAAC;IACDb,GAAG,CAACgF,OAAO,KAAKA,OAAO;IACvB,IAAIhF,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAAoF,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB,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,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,MAAMI,EAAE,IAAIL,GAAG,EAAE;IACpB,IAAIM,QAAQ,GAAGH,UAAU,CAACE,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAAQ;MAAEC,OAAO,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L,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":[]}
|
|
@@ -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","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: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAA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,CAACjE;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAACsE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCnE,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE6C,MAAM,GAAG7B,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGoD,UAAU,CAACtE,SAAS,GAAG,IAAI,GAAGsE,UAAU,CAACrE,IAAI;IACzEuE,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACpE,WAAW,CAAC;IACxCoD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBtC,GAAG,EAAEoC,IAAI,CAACpC,GAAG;IACbhB,SAAS,EAAEsE,UAAU,CAACtE;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: 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,CAA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CAAC;EAED,OAAO;IACLI,IAAI,EAAE6C,MAAM,GAAG7B,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGoD,UAAU,CAACtE,SAAS,GAAG,IAAI,GAAGsE,UAAU,CAACrE,IAAI;IACzEuE,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACpE,WAAW,CAAC;IACxCoD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBtC,GAAG,EAAEoC,IAAI,CAACpC,GAAG;IACbhB,SAAS,EAAEsE,UAAU,CAACtE;EACxB,CAAC;AACH;;AAIA","ignoreList":[]}
|
|
@@ -77,72 +77,71 @@ initialValue
|
|
|
77
77
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
78
78
|
) {
|
|
79
79
|
const globalState = (0, _GlobalStateProvider.getGlobalState)();
|
|
80
|
-
const ref = (0, _react.useRef)(
|
|
81
|
-
|
|
82
|
-
// TODO: Revise how this `rc` variable is used, perhaps we can simplify stuff
|
|
83
|
-
// here.
|
|
84
|
-
let rc = ref.current;
|
|
85
|
-
if (!ref.current) {
|
|
80
|
+
const ref = (0, _react.useRef)(null);
|
|
81
|
+
const [stable] = (0, _react.useState)(() => {
|
|
86
82
|
const emitter = new _jsUtils.Emitter();
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
path
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
console.groupEnd();
|
|
98
|
-
/* eslint-enable no-console */
|
|
99
|
-
}
|
|
100
|
-
rc.globalState.set(rc.path, newState);
|
|
101
|
-
|
|
102
|
-
// NOTE: The regular global state's update notifications, automatically
|
|
103
|
-
// triggered by the rc.globalState.set() call above, are batched, and
|
|
104
|
-
// scheduled to fire asynchronosuly at a later time, which is problematic
|
|
105
|
-
// for managed text inputs - if they have their value update delayed to
|
|
106
|
-
// future render cycles, it will result in reset of their cursor position
|
|
107
|
-
// to the value end. Calling the rc.emitter.emit() below causes a sooner
|
|
108
|
-
// state update for the current component, thus working around the issue.
|
|
109
|
-
// For additional details see the original issue:
|
|
110
|
-
// https://github.com/birdofpreyru/react-global-state/issues/22
|
|
111
|
-
if (newState !== rc.state) rc.emitter.emit();
|
|
112
|
-
},
|
|
113
|
-
state: (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue,
|
|
114
|
-
subscribe: emitter.addListener.bind(emitter),
|
|
115
|
-
watcher: () => {
|
|
116
|
-
// TODO: Revise it later.
|
|
117
|
-
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
118
|
-
const state = rc.globalState.get(rc.path);
|
|
119
|
-
if (state !== rc.state) rc.emitter.emit();
|
|
83
|
+
const setter = value => {
|
|
84
|
+
const rc = ref.current;
|
|
85
|
+
if (!rc) throw Error('Internal error');
|
|
86
|
+
const newState = (0, _lodash.isFunction)(value) ? value(rc.globalState.get(rc.path)) : value;
|
|
87
|
+
if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
|
|
88
|
+
/* eslint-disable no-console */
|
|
89
|
+
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path ?? ''}`);
|
|
90
|
+
console.log('New value:', (0, _utils.cloneDeepForLog)(newState, rc.path ?? ''));
|
|
91
|
+
console.groupEnd();
|
|
92
|
+
/* eslint-enable no-console */
|
|
120
93
|
}
|
|
94
|
+
rc.globalState.set(rc.path, newState);
|
|
95
|
+
|
|
96
|
+
// NOTE: The regular global state's update notifications, automatically
|
|
97
|
+
// triggered by the rc.globalState.set() call above, are batched, and
|
|
98
|
+
// scheduled to fire asynchronosuly at a later time, which is problematic
|
|
99
|
+
// for managed text inputs - if they have their value update delayed to
|
|
100
|
+
// future render cycles, it will result in reset of their cursor position
|
|
101
|
+
// to the value end. Calling the rc.emitter.emit() below causes a sooner
|
|
102
|
+
// state update for the current component, thus working around the issue.
|
|
103
|
+
// For additional details see the original issue:
|
|
104
|
+
// https://github.com/birdofpreyru/react-global-state/issues/22
|
|
105
|
+
if (newState !== rc.prevValue) emitter.emit();
|
|
106
|
+
};
|
|
107
|
+
const subscribe = emitter.addListener.bind(emitter);
|
|
108
|
+
return {
|
|
109
|
+
emitter,
|
|
110
|
+
setter,
|
|
111
|
+
subscribe
|
|
121
112
|
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
rc.globalState = globalState;
|
|
125
|
-
rc.path = path;
|
|
126
|
-
rc.state = (0, _react.useSyncExternalStore)(rc.subscribe, () => rc.globalState.get(rc.path, {
|
|
113
|
+
});
|
|
114
|
+
const value = (0, _react.useSyncExternalStore)(stable.subscribe, () => globalState.get(path, {
|
|
127
115
|
initialValue
|
|
128
|
-
}), () =>
|
|
116
|
+
}), () => globalState.get(path, {
|
|
129
117
|
initialState: true,
|
|
130
118
|
initialValue
|
|
131
119
|
}));
|
|
120
|
+
ref.current ??= {
|
|
121
|
+
globalState,
|
|
122
|
+
path,
|
|
123
|
+
prevValue: value
|
|
124
|
+
};
|
|
132
125
|
(0, _react.useEffect)(() => {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
126
|
+
ref.current = {
|
|
127
|
+
globalState,
|
|
128
|
+
path,
|
|
129
|
+
prevValue: ref.current.prevValue
|
|
130
|
+
};
|
|
131
|
+
const watcher = () => {
|
|
132
|
+
const nextValue = globalState.get(path);
|
|
133
|
+
if (ref.current.prevValue !== nextValue) {
|
|
134
|
+
ref.current.prevValue = nextValue;
|
|
135
|
+
stable.emitter.emit();
|
|
136
|
+
}
|
|
137
|
+
};
|
|
136
138
|
globalState.watch(watcher);
|
|
137
139
|
watcher();
|
|
138
140
|
return () => {
|
|
139
141
|
globalState.unWatch(watcher);
|
|
140
142
|
};
|
|
141
|
-
}, [globalState]);
|
|
142
|
-
|
|
143
|
-
ref.current.watcher();
|
|
144
|
-
}, [path]);
|
|
145
|
-
return [rc.state, rc.setter];
|
|
143
|
+
}, [globalState, stable.emitter, path]);
|
|
144
|
+
return [value, stable.setter];
|
|
146
145
|
}
|
|
147
146
|
var _default = exports.default = useGlobalState; // TODO: Revise.
|
|
148
147
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|