@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.
- package/build/cjs/GlobalStateProvider.js +15 -12
- package/build/cjs/GlobalStateProvider.js.map +1 -1
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/useAsyncCollection.js +67 -65
- package/build/cjs/useAsyncCollection.js.map +1 -1
- package/build/cjs/useAsyncData.js +35 -22
- 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/index.js.map +1 -1
- package/build/code/useAsyncCollection.js +69 -67
- package/build/code/useAsyncCollection.js.map +1 -1
- package/build/code/useAsyncData.js +36 -23
- package/build/code/useAsyncData.js.map +1 -1
- package/build/code/useGlobalState.js +55 -55
- package/build/code/useGlobalState.js.map +1 -1
- package/build/types/index.d.ts +1 -1
- package/build/types/useAsyncData.d.ts +1 -0
- package/package.json +20 -19
|
@@ -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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","undefined","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>(undefined);\n\n // TODO: Revise how this `rc` variable is used, perhaps we can simplify stuff\n // here.\n let rc: GlobalStateRef | undefined = ref.current;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path)) as unknown\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc!.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n // TODO: Revise it later.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const state = rc!.globalState.get(rc!.path) as unknown;\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue }),\n\n () => rc.globalState.get<ForceT, unknown>(\n rc.path,\n { initialState: true, initialValue },\n ),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAQA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAjBA;;AA4CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAkBA,SAASK,cAAcA,CACrBC,IAAoB;AACpB;AACA;AACAC;;AAEA;AACA;AAAA,EACyB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAiBC,SAAS,CAAC;;EAE7C;EACA;EACA,IAAIC,EAA8B,GAAGH,GAAG,CAACI,OAAO;EAChD,IAAI,CAACJ,GAAG,CAACI,OAAO,EAAE;IAChB,MAAMC,OAAO,GAAG,IAAIC,gBAAO,CAAC,CAAC;IAC7BN,GAAG,CAACI,OAAO,GAAG;MACZC,OAAO;MACPP,WAAW;MACXF,IAAI;MACJW,MAAM,EAAGC,KAAK,IAAK;QACjB,MAAMC,QAAQ,GAAG,IAAAC,kBAAU,EAACF,KAAK,CAAC,GAC9BA,KAAK,CAACL,EAAE,CAAEL,WAAW,CAACa,GAAG,CAACR,EAAE,CAAEP,IAAI,CAAC,CAAC,GACpCY,KAAK;QAET,IAAII,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;UAC1D;U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EAAE,CAACL,WAAW,CAACa,GAAG,CACtBR,EAAE,CAACP,IAAI,EACP;IAAEiC,YAAY,EAAE,IAAI;IAAEhC;EAAa,CACrC,CACF,CAAC;EAED,IAAAiC,gBAAS,EAAC,MAAM;IACd,MAAM;MAAEH;IAAQ,CAAC,GAAG3B,GAAG,CAACI,OAAQ;IAChCN,WAAW,CAACiC,KAAK,CAACJ,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM;MACX7B,WAAW,CAACkC,OAAO,CAACL,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAC7B,WAAW,CAAC,CAAC;EAEjB,IAAAgC,gBAAS,EAAC,MAAM;IACd9B,GAAG,CAACI,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC/B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACO,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcxC,cAAc,EAE7B;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","stable","useState","emitter","Emitter","setter","value","rc","current","Error","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","prevValue","emit","subscribe","addListener","bind","useSyncExternalStore","initialState","useEffect","watcher","nextValue","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = isFunction(value)\n ? value(rc.globalState.get(rc.path)) as unknown\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AASA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAlBA;;AA8CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AASA;;AAGA;;AAkBA,SAASK,cAAcA,CACrBC,IAAoB;AACpB;AACA;AACAC;;AAEA;AACA;AAAA,EACyB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAW,IAAI,CAAC;EAElC,MAAM,CAACC,MAAM,CAAC,GAAG,IAAAC,eAAQ,EAAU,MAAM;IACvC,MAAMC,OAAO,GAAG,IAAIC,gBAAO,CAAC,CAAC;IAC7B,MAAMC,MAAM,GAAIC,KAAc,IAAK;MACjC,MAAMC,EAAE,GAAGR,GAAG,CAACS,OAAO;MACtB,IAAI,CAACD,EAAE,EAAE,MAAME,KAAK,CAAC,gBAAgB,CAAC;MAEtC,MAAMC,QAAQ,GAAG,IAAAC,kBAAU,EAACL,KAAK,CAAC,GAC9BA,KAAK,CAACC,EAAE,CAACV,WAAW,CAACe,GA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MACJ4B,SAAS,EAAExB,GAAG,CAACS,OAAO,CAAEe;IAC1B,CAAC;IAED,MAAMQ,OAAO,GAAGA,CAAA,KAAM;MACpB,MAAMC,SAAS,GAAGnC,WAAW,CAACe,GAAG,CAAkBjB,IAAI,CAAC;MACxD,IAAII,GAAG,CAACS,OAAO,CAAEe,SAAS,KAAKS,SAAS,EAAE;QACxCjC,GAAG,CAACS,OAAO,CAAEe,SAAS,GAAGS,SAAS;QAClC/B,MAAM,CAACE,OAAO,CAACqB,IAAI,CAAC,CAAC;MACvB;IACF,CAAC;IAED3B,WAAW,CAACoC,KAAK,CAACF,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IAET,OAAO,MAAM;MACXlC,WAAW,CAACqC,OAAO,CAACH,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAClC,WAAW,EAAEI,MAAM,CAACE,OAAO,EAAER,IAAI,CAAC,CAAC;EAEvC,OAAO,CAACW,KAAK,EAAEL,MAAM,CAACI,MAAM,CAAC;AAC/B;AAAC,IAAA8B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc3C,cAAc,EAE7B;AACA","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isFunction } from 'lodash';
|
|
2
|
-
import { createContext, use,
|
|
2
|
+
import { createContext, use, useState } from 'react';
|
|
3
3
|
import GlobalState from "./GlobalState";
|
|
4
4
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
5
5
|
const Context = /*#__PURE__*/createContext(null);
|
|
@@ -62,22 +62,25 @@ const GlobalStateProvider = ({
|
|
|
62
62
|
children,
|
|
63
63
|
...rest
|
|
64
64
|
}) => {
|
|
65
|
-
const
|
|
65
|
+
const [localState, setLocalState] = useState();
|
|
66
66
|
let state;
|
|
67
|
-
|
|
68
|
-
//
|
|
67
|
+
|
|
68
|
+
// Below we cast `rest.stateProxy` as "boolean" for safe backward
|
|
69
|
+
// compatibility with plain JavaScript (as TypeScript typings only
|
|
70
|
+
// permit "true" or GlobalState value; while legacy codebase may
|
|
71
|
+
// pass in a boolean value here, occasionally equal "false").
|
|
69
72
|
if ('stateProxy' in rest && rest.stateProxy) {
|
|
70
|
-
|
|
73
|
+
if (localState) setLocalState(undefined);
|
|
71
74
|
state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
|
|
75
|
+
} else if (localState) {
|
|
76
|
+
state = localState;
|
|
72
77
|
} else {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
state = localStateRef.current;
|
|
78
|
+
const {
|
|
79
|
+
initialState,
|
|
80
|
+
ssrContext
|
|
81
|
+
} = rest;
|
|
82
|
+
state = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
|
|
83
|
+
setLocalState(state);
|
|
81
84
|
}
|
|
82
85
|
return /*#__PURE__*/_jsx(Context, {
|
|
83
86
|
value: state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","use","
|
|
1
|
+
{"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","use","useState","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localState","setLocalState","state","stateProxy","undefined","initialState","value"],"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,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,GAAG,EACHC,QAAQ,QACH,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGL,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACK,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,GAAGf,QAAQ,CAAM,CAAC;EAEnD,IAAIgB,KAAU;;EAEd;EACA;EACA;EACA;EACA,IAAI,YAAY,IAAIH,IAAI,IAAKA,IAAI,CAACI,UAAsB,EAAE;IACxD,IAAIH,UAAU,EAAEC,aAAa,CAACG,SAAS,CAAC;IACxCF,KAAK,GAAGH,IAAI,CAACI,UAAU,KAAK,IAAI,GAAGZ,cAAc,CAAC,CAAC,GAAGQ,IAAI,CAACI,UAAU;EACvE,CAAC,MAAM,IAAIH,UAAU,EAAE;IACrBE,KAAK,GAAGF,UAAU;EACpB,CAAC,MAAM;IACL,MAAM;MACJK,YAAY;MACZT;IACF,CAAC,GAAGG,IAA0C;IAE9CG,KAAK,GAAG,IAAIf,WAAW,CACrBJ,UAAU,CAACsB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDT,UACF,CAAC;IAEDK,aAAa,CAACC,KAAK,CAAC;EACtB;EAEA,oBAAOb,IAAA,CAACC,OAAO;IAACgB,KAAK,EAAEJ,KAAM;IAAAJ,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeD,mBAAmB","ignoreList":[]}
|
package/build/code/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n 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 {
|
|
1
|
+
{"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n 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":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAKzB,SAOEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAYrB,SAOEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;;AAGhB;;AAgBA,MAAMC,GAAG,GAAG;EACV;EACA;EACA;EACAT,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVF,cAAc;EACdC,aAAa;EACbG,oBAAoB;EACpBD,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Loads and uses item(s) in an async collection.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { useEffect, useRef } from 'react';
|
|
5
|
+
import { useEffect, useRef, useState } from 'react';
|
|
6
6
|
import { v4 as uuid } from 'uuid';
|
|
7
7
|
import { getGlobalState } from "./GlobalStateProvider";
|
|
8
8
|
import { DEFAULT_MAXAGE, load, newAsyncDataEnvelope } from "./useAsyncData";
|
|
@@ -82,68 +82,6 @@ function normalizeIds(idOrIds) {
|
|
|
82
82
|
return [idOrIds];
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
/**
|
|
86
|
-
* Inits/updates, and returns the heap.
|
|
87
|
-
*/
|
|
88
|
-
function useHeap(ids, path, loader, gs) {
|
|
89
|
-
const ref = useRef(undefined);
|
|
90
|
-
let heap = ref.current;
|
|
91
|
-
if (heap) {
|
|
92
|
-
// Update.
|
|
93
|
-
heap.ids = ids;
|
|
94
|
-
heap.path = path;
|
|
95
|
-
heap.loader = loader;
|
|
96
|
-
heap.globalState = gs;
|
|
97
|
-
} else {
|
|
98
|
-
// Initialization.
|
|
99
|
-
const reload = async customLoader => {
|
|
100
|
-
const heap2 = ref.current;
|
|
101
|
-
const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : heap2.loader;
|
|
102
|
-
// TODO: Revise - not sure all related typing is 100% correct,
|
|
103
|
-
// thus let's keep this runtime assertion.
|
|
104
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
105
|
-
if (!localLoader || !heap2.globalState || !heap2.ids) {
|
|
106
|
-
throw Error('Internal error');
|
|
107
|
-
}
|
|
108
|
-
for (const id of heap2.ids) {
|
|
109
|
-
const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
|
|
110
|
-
const promiseOrVoid = load(itemPath,
|
|
111
|
-
// TODO: Revise! Most probably we don't have fully correct loader
|
|
112
|
-
// typing, as it may return either promise or value, and those two
|
|
113
|
-
// cases call for different runtime behavior, which in turns only
|
|
114
|
-
// happens if the outer function on the next line matches the same
|
|
115
|
-
// async / sync signature.
|
|
116
|
-
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
117
|
-
(oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
|
|
118
|
-
if (promiseOrVoid instanceof Promise) await promiseOrVoid;
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
heap = {
|
|
122
|
-
globalState: gs,
|
|
123
|
-
ids,
|
|
124
|
-
loader,
|
|
125
|
-
path,
|
|
126
|
-
reload,
|
|
127
|
-
// TODO: Revise! Most probably we don't have fully correct loader
|
|
128
|
-
// typing, as it may return either promise or value, and those two
|
|
129
|
-
// cases call for different runtime behavior, which in turns only
|
|
130
|
-
// happens if the outer function on the next line matches the same
|
|
131
|
-
// async / sync signature.
|
|
132
|
-
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
133
|
-
reloadSingle: customLoader => ref.current.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
|
-
customLoader && ((id, ...args) => customLoader(...args)))
|
|
141
|
-
};
|
|
142
|
-
ref.current = heap;
|
|
143
|
-
}
|
|
144
|
-
return heap;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
85
|
/**
|
|
148
86
|
* Resolves and stores at the given `path` of the global state elements of
|
|
149
87
|
* an asynchronous data collection.
|
|
@@ -154,13 +92,12 @@ function useHeap(ids, path, loader, gs) {
|
|
|
154
92
|
// and reused in both hooks.
|
|
155
93
|
// eslint-disable-next-line complexity
|
|
156
94
|
function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
157
|
-
var _options$maxage, _options$refreshAge, _options$garbageColle;
|
|
95
|
+
var _options$maxage, _options$refreshAge, _options$garbageColle, _ref$current;
|
|
158
96
|
const ids = normalizeIds(idOrIds);
|
|
159
97
|
const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
|
|
160
98
|
const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
|
|
161
99
|
const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
|
|
162
100
|
const globalState = getGlobalState();
|
|
163
|
-
const heap = useHeap(ids, path, loader, globalState);
|
|
164
101
|
|
|
165
102
|
// Server-side logic.
|
|
166
103
|
if (globalState.ssrContext) {
|
|
@@ -241,6 +178,70 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
241
178
|
});
|
|
242
179
|
}
|
|
243
180
|
const [localState] = useGlobalState(path, {});
|
|
181
|
+
const ref = useRef(null);
|
|
182
|
+
(_ref$current = ref.current) !== null && _ref$current !== void 0 ? _ref$current : ref.current = {
|
|
183
|
+
globalState,
|
|
184
|
+
ids,
|
|
185
|
+
loader,
|
|
186
|
+
path
|
|
187
|
+
};
|
|
188
|
+
useEffect(() => {
|
|
189
|
+
ref.current = {
|
|
190
|
+
globalState,
|
|
191
|
+
ids,
|
|
192
|
+
loader,
|
|
193
|
+
path
|
|
194
|
+
};
|
|
195
|
+
}, [globalState, ids, loader, path]);
|
|
196
|
+
const [stable] = useState(() => {
|
|
197
|
+
const reload = async customLoader => {
|
|
198
|
+
const rc = ref.current;
|
|
199
|
+
if (!rc) throw Error('Internal error');
|
|
200
|
+
const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : rc.loader;
|
|
201
|
+
|
|
202
|
+
// TODO: Revise - not sure all related typing is 100% correct,
|
|
203
|
+
// thus let's keep this runtime assertion.
|
|
204
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
205
|
+
if (!localLoader || !rc.globalState || !rc.ids) {
|
|
206
|
+
throw Error('Internal error');
|
|
207
|
+
}
|
|
208
|
+
for (const id of rc.ids) {
|
|
209
|
+
const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;
|
|
210
|
+
const promiseOrVoid = load(itemPath,
|
|
211
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
212
|
+
// typing, as it may return either promise or value, and those two
|
|
213
|
+
// cases call for different runtime behavior, which in turns only
|
|
214
|
+
// happens if the outer function on the next line matches the same
|
|
215
|
+
// async / sync signature.
|
|
216
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
217
|
+
(oldData, meta) => localLoader(id, oldData, meta), rc.globalState);
|
|
218
|
+
if (promiseOrVoid instanceof Promise) await promiseOrVoid;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
223
|
+
// typing, as it may return either promise or value, and those two
|
|
224
|
+
// cases call for different runtime behavior, which in turns only
|
|
225
|
+
// happens if the outer function on the next line matches the same
|
|
226
|
+
// async / sync signature.
|
|
227
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
228
|
+
const reloadSingle = customLoader => reload(
|
|
229
|
+
// TODO: Revise! Most probably we don't have fully correct loader
|
|
230
|
+
// typing, as it may return either promise or value, and those two
|
|
231
|
+
// cases call for different runtime behavior, which in turns only
|
|
232
|
+
// happens if the outer function on the next line matches the same
|
|
233
|
+
// async / sync signature.
|
|
234
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
235
|
+
customLoader && ((id, ...args) => customLoader(...args)));
|
|
236
|
+
const setSingle = data => {
|
|
237
|
+
void reload(() => data);
|
|
238
|
+
};
|
|
239
|
+
return {
|
|
240
|
+
reload,
|
|
241
|
+
reloadSingle,
|
|
242
|
+
setSingle
|
|
243
|
+
};
|
|
244
|
+
});
|
|
244
245
|
if (!Array.isArray(idOrIds)) {
|
|
245
246
|
var _e$timestamp, _e$data;
|
|
246
247
|
// TODO: Revise related typings!
|
|
@@ -249,14 +250,15 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
|
|
|
249
250
|
return {
|
|
250
251
|
data: maxage < Date.now() - timestamp ? null : (_e$data = e === null || e === void 0 ? void 0 : e.data) !== null && _e$data !== void 0 ? _e$data : null,
|
|
251
252
|
loading: !!(e !== null && e !== void 0 && e.operationId),
|
|
252
|
-
reload:
|
|
253
|
+
reload: stable.reloadSingle,
|
|
254
|
+
set: stable.setSingle,
|
|
253
255
|
timestamp
|
|
254
256
|
};
|
|
255
257
|
}
|
|
256
258
|
const res = {
|
|
257
259
|
items: {},
|
|
258
260
|
loading: false,
|
|
259
|
-
reload:
|
|
261
|
+
reload: stable.reload,
|
|
260
262
|
timestamp: Number.MAX_VALUE
|
|
261
263
|
};
|
|
262
264
|
for (const id of ids) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useHeap","loader","ref","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","_options$maxage","_options$refreshAge","_options$garbageColle","maxage","refreshAge","garbageCollectAge","ssrContext","disabled","noSSR","operationId","state","initialValue","data","pending","push","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","localState","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"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}`>, IdT>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,IAAI,EACJC,WAAW;AAoDb;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,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,EAAE,CAAC,GAAGD,QAAQ,CAACC;IAAQ,CAAC,CAAC,KACnED,QAAQ,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D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe+C,kBAAkB;;AAEjC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","useState","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","_options$maxage","_options$refreshAge","_options$garbageColle","_ref$current","maxage","refreshAge","garbageCollectAge","globalState","ssrContext","disabled","noSSR","operationId","itemPath","state","initialValue","promiseOrVoid","args","data","Promise","pending","push","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","localState","ref","current","stable","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"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":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,OAAO;AACnD,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIE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