@dr.pogodin/react-global-state 0.10.0-alpha.1 → 0.10.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -327
- package/build/common/GlobalState.js +219 -0
- package/build/common/GlobalState.js.map +1 -0
- package/build/common/GlobalStateProvider.js +101 -0
- package/build/common/GlobalStateProvider.js.map +1 -0
- package/build/common/SsrContext.js +15 -0
- package/build/common/SsrContext.js.map +1 -0
- package/build/common/index.js +76 -0
- package/build/common/index.js.map +1 -0
- package/build/common/useAsyncCollection.js +61 -0
- package/build/common/useAsyncCollection.js.map +1 -0
- package/build/common/useAsyncData.js +204 -0
- package/build/common/useAsyncData.js.map +1 -0
- package/build/common/useGlobalState.js +113 -0
- package/build/common/useGlobalState.js.map +1 -0
- package/build/common/utils.js +44 -0
- package/build/common/utils.js.map +1 -0
- package/build/common/withGlobalStateType.js +42 -0
- package/build/common/withGlobalStateType.js.map +1 -0
- package/build/module/GlobalState.js +230 -0
- package/build/module/GlobalState.js.map +1 -0
- package/build/module/GlobalStateProvider.js +94 -0
- package/build/module/GlobalStateProvider.js.map +1 -0
- package/build/module/SsrContext.js +9 -0
- package/build/module/SsrContext.js.map +1 -0
- package/build/module/index.js +8 -0
- package/build/module/index.js.map +1 -0
- package/build/module/useAsyncCollection.js +56 -0
- package/build/module/useAsyncCollection.js.map +1 -0
- package/build/module/useAsyncData.js +199 -0
- package/build/module/useAsyncData.js.map +1 -0
- package/build/module/useGlobalState.js +108 -0
- package/build/module/useGlobalState.js.map +1 -0
- package/build/module/utils.js +35 -0
- package/build/module/utils.js.map +1 -0
- package/build/module/withGlobalStateType.js +35 -0
- package/build/module/withGlobalStateType.js.map +1 -0
- package/build/types/GlobalState.d.ts +75 -0
- package/build/types/GlobalStateProvider.d.ts +55 -0
- package/build/types/SsrContext.d.ts +6 -0
- package/build/types/index.d.ts +8 -0
- package/build/types/useAsyncCollection.d.ts +51 -0
- package/build/types/useAsyncData.d.ts +75 -0
- package/build/types/useGlobalState.d.ts +58 -0
- package/build/types/utils.d.ts +34 -0
- package/build/types/withGlobalStateType.d.ts +29 -0
- package/package.json +42 -41
- package/src/GlobalState.ts +283 -0
- package/src/GlobalStateProvider.tsx +127 -0
- package/src/SsrContext.ts +11 -0
- package/src/index.ts +33 -0
- package/src/useAsyncCollection.ts +96 -0
- package/src/useAsyncData.ts +295 -0
- package/src/useGlobalState.ts +156 -0
- package/src/utils.ts +64 -0
- package/src/withGlobalStateType.ts +170 -0
- package/tsconfig.json +9 -3
- package/tsconfig.types.json +14 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","state","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","set","watcher","get","emit","useSyncExternalStore","cb","addListener","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\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\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\nfunction useGlobalState<Forced extends ForceT | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\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 initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n const rc: GlobalStateRef = ref.current || {\n emitter: new Emitter(),\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value) ? value(rc.state) : value;\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:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n watcher: () => {\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) rc.emitter.emit();\n },\n };\n ref.current = rc;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => rc.emitter.addListener(cb),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue }),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAgCA;AACA;AACA;AACA;AACA;A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
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.isDebugMode = isDebugMode;
|
|
7
|
+
// TODO: This (ForceT & TypeLock) probably should be moved to JS Utils lib.
|
|
8
|
+
|
|
9
|
+
// This type is used to "unlocked" special generic overrides around the library.
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Given the type of state, `StateT`, and the type of state path, `PathT`,
|
|
13
|
+
* it evaluates the type of value at that path of the state, if it can be
|
|
14
|
+
* evaluated from the path type (it is possible when `PathT` is a string
|
|
15
|
+
* literal type, and `StateT` elements along this path have appropriate
|
|
16
|
+
* types); otherwise it falls back to the specified `UnknownT` type,
|
|
17
|
+
* which should be set either `never` (for input arguments), or `void`
|
|
18
|
+
* (for return types) - `never` and `void` in those places forbid assignments,
|
|
19
|
+
* and are not auto-inferred to more permissible types.
|
|
20
|
+
*
|
|
21
|
+
* BEWARE: When StateT is any the construct resolves to any for any string
|
|
22
|
+
* paths.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Returns 'true' if debug logging should be performed; 'false' otherwise.
|
|
27
|
+
*
|
|
28
|
+
* BEWARE: The actual safeguards for the debug logging still should read
|
|
29
|
+
* if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
30
|
+
* // Some debug logging
|
|
31
|
+
* }
|
|
32
|
+
* to ensure that debug code is stripped out by Webpack in production mode.
|
|
33
|
+
*
|
|
34
|
+
* @returns
|
|
35
|
+
* @ignore
|
|
36
|
+
*/
|
|
37
|
+
function isDebugMode() {
|
|
38
|
+
try {
|
|
39
|
+
return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT & TypeLock) probably should be moved to JS Utils lib.\n\n// This type is used to \"unlocked\" special generic overrides around the library.\ndeclare const force: unique symbol;\nexport type ForceT = typeof force;\n\nexport type TypeLock<\n Unlocked extends ForceT | false,\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n"],"mappings":";;;;;;AAIA;;AAEA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
exports.default = withGlobalStateType;
|
|
8
|
+
var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
|
|
9
|
+
var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
|
|
10
|
+
var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
|
|
11
|
+
var _useAsyncData = _interopRequireDefault(require("./useAsyncData"));
|
|
12
|
+
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
|
13
|
+
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
|
14
|
+
function withGlobalStateType() {
|
|
15
|
+
// These wrap useGlobalState() with locked-in StateT type.
|
|
16
|
+
|
|
17
|
+
function useGlobalStateWrap(path, initialValue) {
|
|
18
|
+
return (0, _useGlobalState.default)(path, initialValue);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// These overloads & implementation wrap useAsyncData() hook to lock-in its
|
|
22
|
+
// underlying StateT.
|
|
23
|
+
function useAsyncDataWrap(path, loader, options = {}) {
|
|
24
|
+
return (0, _useAsyncData.default)(path, loader, options);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// These overloads & implementation wrap useAsyncCollection() hook to lock-in
|
|
28
|
+
// its underlying StateT.
|
|
29
|
+
function useAsyncCollectionWrap(id, path, loader, options = {}) {
|
|
30
|
+
return (0, _useAsyncCollection.default)(id, path, loader, options);
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
getGlobalState: _GlobalStateProvider.getGlobalState,
|
|
34
|
+
getSsrContext: _GlobalStateProvider.getSsrContext,
|
|
35
|
+
GlobalStateProvider: _GlobalStateProvider.default,
|
|
36
|
+
// SsrContext, /* CustomSsrContext || SsrContext, */
|
|
37
|
+
useAsyncCollection: useAsyncCollectionWrap,
|
|
38
|
+
useAsyncData: useAsyncDataWrap,
|
|
39
|
+
useGlobalState: useGlobalStateWrap
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=withGlobalStateType.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"withGlobalStateType.js","names":["_GlobalStateProvider","_interopRequireWildcard","require","_useGlobalState","_interopRequireDefault","_useAsyncCollection","_useAsyncData","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","withGlobalStateType","useGlobalStateWrap","path","initialValue","useGlobalState","useAsyncDataWrap","loader","options","useAsyncData","useAsyncCollectionWrap","id","useAsyncCollection","getGlobalState","getSsrContext","GlobalStateProvider"],"sources":["../../src/withGlobalStateType.ts"],"sourcesContent":["import {\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n} from './utils';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useGlobalState, {\n type UseGlobalStateResT,\n} from './useGlobalState';\n\nimport useAsyncCollection, {\n type AsyncCollectionLoaderT,\n} from './useAsyncCollection';\n\nimport useAsyncData, {\n type AsyncDataLoaderT,\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\ninterface NarrowedUseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\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 | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n\ninterface NarrowedUseAsyncDataI<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 | false = false, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, never, DataT>>;\n}\n\ninterface NarrowedUseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined>(\n id: string,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | false = false, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataT>;\n}\n\ntype WithGlobalStateTypeResT<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> = {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>,\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n // SsrContext: SsrContext<StateT>,\n useAsyncCollection: NarrowedUseAsyncCollectionI<StateT>,\n useAsyncData: NarrowedUseAsyncDataI<StateT>,\n useGlobalState: NarrowedUseGlobalStateI<StateT>,\n};\n\nexport default function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): WithGlobalStateTypeResT<StateT, SsrContextT> {\n // These wrap useGlobalState() with locked-in StateT type.\n\n function useGlobalStateWrap(): UseGlobalStateResT<StateT>;\n\n function useGlobalStateWrap<PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n function useGlobalStateWrap<Forced extends ForceT | false = false, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n function useGlobalStateWrap(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n ): UseGlobalStateResT<any> {\n return useGlobalState<ForceT, unknown>(path, initialValue);\n }\n\n // These overloads & implementation wrap useAsyncData() hook to lock-in its\n // underlying StateT.\n\n function useAsyncDataWrap<PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n function useAsyncDataWrap<Forced extends ForceT | false = false, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, never, DataT>>;\n\n function useAsyncDataWrap<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n ): UseAsyncDataResT<DataT> {\n return useAsyncData<ForceT, DataT>(path, loader, options);\n }\n\n // These overloads & implementation wrap useAsyncCollection() hook to lock-in\n // its underlying StateT.\n\n function useAsyncCollectionWrap<PathT extends null | string | undefined>(\n id: string,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n function useAsyncCollectionWrap<Forced extends ForceT | false = false, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataT>;\n\n function useAsyncCollectionWrap<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n ): UseAsyncDataResT<DataT> {\n return useAsyncCollection<ForceT, DataT>(id, path, loader, options);\n }\n\n return {\n getGlobalState: getGlobalState<StateT, SsrContextT>,\n getSsrContext: getSsrContext<SsrContextT>,\n GlobalStateProvider: GlobalStateProvider<StateT, SsrContextT>,\n // SsrContext, /* CustomSsrContext || SsrContext, */\n useAsyncCollection: useAsyncCollectionWrap,\n useAsyncData: useAsyncDataWrap,\n useGlobalState: useGlobalStateWrap,\n };\n}\n"],"mappings":";;;;;;;AAOA,IAAAA,oBAAA,GAAAC,uBAAA,CAAAC,OAAA;AAOA,IAAAC,eAAA,GAAAC,sBAA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mBA,CAAA,EAGO;EAChD;;EAcA,SAASC,kBAAkBA,CACzBC,IAAoB,EACpBC,YAA2C,EAClB;IACzB,OAAO,IAAAC,uBAAc,EAAkBF,IAAI,EAAEC,YAAY,CAAC;EAC5D;;EAEA;EACA;EAcA,SAASE,gBAAgBA,CACvBH,IAA+B,EAC/BI,MAA+B,EAC/BC,OAA6B,GAAG,CAAC,CAAC,EACT;IACzB,OAAO,IAAAC,qBAAY,EAAgBN,IAAI,EAAEI,MAAM,EAAEC,OAAO,CAAC;EAC3D;;EAEA;EACA;EAgBA,SAASE,sBAAsBA,CAC7BC,EAAU,EACVR,IAA+B,EAC/BI,MAAqC,EACrCC,OAA6B,GAAG,CAAC,CAAC,EACT;IACzB,OAAO,IAAAI,2BAAkB,EAAgBD,EAAE,EAAER,IAAI,EAAEI,MAAM,EAAEC,OAAO,CAAC;EACrE;EAEA,OAAO;IACLK,cAAc,EAAEA,mCAAmC;IACnDC,aAAa,EAAEA,kCAA0B;IACzCC,mBAAmB,EAAEA,4BAAwC;IAC7D;IACAH,kBAAkB,EAAEF,sBAAsB;IAC1CD,YAAY,EAAEH,gBAAgB;IAC9BD,cAAc,EAAEH;EAClB,CAAC;AACH"}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import _classPrivateFieldGet from "@babel/runtime/helpers/classPrivateFieldGet";
|
|
2
|
+
import _classPrivateFieldSet from "@babel/runtime/helpers/classPrivateFieldSet";
|
|
3
|
+
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
|
|
4
|
+
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
|
|
5
|
+
import { cloneDeep, get, isFunction, isObject, isNil, set, toPath } from 'lodash';
|
|
6
|
+
import { isDebugMode } from "./utils";
|
|
7
|
+
const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
|
|
8
|
+
var _initialState = /*#__PURE__*/new WeakMap();
|
|
9
|
+
var _watchers = /*#__PURE__*/new WeakMap();
|
|
10
|
+
var _nextNotifierId = /*#__PURE__*/new WeakMap();
|
|
11
|
+
var _currentState = /*#__PURE__*/new WeakMap();
|
|
12
|
+
export default class GlobalState {
|
|
13
|
+
/**
|
|
14
|
+
* Creates a new global state object.
|
|
15
|
+
* @param initialState Intial global state content.
|
|
16
|
+
* @param ssrContext Server-side rendering context.
|
|
17
|
+
*/
|
|
18
|
+
constructor(initialState, ssrContext) {
|
|
19
|
+
_classPrivateFieldInitSpec(this, _initialState, {
|
|
20
|
+
writable: true,
|
|
21
|
+
value: void 0
|
|
22
|
+
});
|
|
23
|
+
// TODO: It is tempting to replace watchers here by
|
|
24
|
+
// Emitter from @dr.pogodin/js-utils, but we need to clone
|
|
25
|
+
// current watchers for emitting later, and this is not something
|
|
26
|
+
// Emitter supports right now.
|
|
27
|
+
_classPrivateFieldInitSpec(this, _watchers, {
|
|
28
|
+
writable: true,
|
|
29
|
+
value: []
|
|
30
|
+
});
|
|
31
|
+
_classPrivateFieldInitSpec(this, _nextNotifierId, {
|
|
32
|
+
writable: true,
|
|
33
|
+
value: void 0
|
|
34
|
+
});
|
|
35
|
+
_classPrivateFieldInitSpec(this, _currentState, {
|
|
36
|
+
writable: true,
|
|
37
|
+
value: void 0
|
|
38
|
+
});
|
|
39
|
+
_classPrivateFieldSet(this, _currentState, initialState);
|
|
40
|
+
_classPrivateFieldSet(this, _initialState, initialState);
|
|
41
|
+
if (ssrContext) {
|
|
42
|
+
/* eslint-disable no-param-reassign */
|
|
43
|
+
ssrContext.dirty = false;
|
|
44
|
+
ssrContext.pending = [];
|
|
45
|
+
ssrContext.state = _classPrivateFieldGet(this, _currentState);
|
|
46
|
+
/* eslint-enable no-param-reassign */
|
|
47
|
+
|
|
48
|
+
this.ssrContext = ssrContext;
|
|
49
|
+
}
|
|
50
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
51
|
+
/* eslint-disable no-console */
|
|
52
|
+
let msg = 'New ReactGlobalState created';
|
|
53
|
+
if (ssrContext) msg += ' (SSR mode)';
|
|
54
|
+
console.groupCollapsed(msg);
|
|
55
|
+
console.log('Initial state:', cloneDeep(initialState));
|
|
56
|
+
console.groupEnd();
|
|
57
|
+
/* eslint-enable no-console */
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Gets entire state, the same way as .get(null, opts) would do.
|
|
63
|
+
* @param opts.initialState
|
|
64
|
+
* @param opts.initialValue
|
|
65
|
+
*/
|
|
66
|
+
getEntireState(opts) {
|
|
67
|
+
let state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
|
|
68
|
+
if (state !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return state;
|
|
69
|
+
const iv = opts.initialValue;
|
|
70
|
+
state = isFunction(iv) ? iv() : iv;
|
|
71
|
+
if (_classPrivateFieldGet(this, _currentState) === undefined) this.setEntireState(state);
|
|
72
|
+
return state;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Notifies all connected state watchers that a state update has happened.
|
|
77
|
+
*/
|
|
78
|
+
notifyStateUpdate(path, value) {
|
|
79
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
80
|
+
/* eslint-disable no-console */
|
|
81
|
+
const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
|
|
82
|
+
console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
|
|
83
|
+
console.log('New value:', cloneDeep(value));
|
|
84
|
+
console.log('New state:', cloneDeep(_classPrivateFieldGet(this, _currentState)));
|
|
85
|
+
console.groupEnd();
|
|
86
|
+
/* eslint-enable no-console */
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (this.ssrContext) {
|
|
90
|
+
this.ssrContext.dirty = true;
|
|
91
|
+
this.ssrContext.state = _classPrivateFieldGet(this, _currentState);
|
|
92
|
+
} else if (!_classPrivateFieldGet(this, _nextNotifierId)) {
|
|
93
|
+
_classPrivateFieldSet(this, _nextNotifierId, setTimeout(() => {
|
|
94
|
+
_classPrivateFieldSet(this, _nextNotifierId, undefined);
|
|
95
|
+
const watchers = [..._classPrivateFieldGet(this, _watchers)];
|
|
96
|
+
for (let i = 0; i < watchers.length; ++i) {
|
|
97
|
+
watchers[i]();
|
|
98
|
+
}
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Sets entire state, the same way as .set(null, value) would do.
|
|
105
|
+
* @param value
|
|
106
|
+
*/
|
|
107
|
+
setEntireState(value) {
|
|
108
|
+
if (_classPrivateFieldGet(this, _currentState) !== value) {
|
|
109
|
+
_classPrivateFieldSet(this, _currentState, value);
|
|
110
|
+
this.notifyStateUpdate(null, value);
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Gets current or initial value at the specified "path" of the global state.
|
|
117
|
+
* @param path Dot-delimitered state path.
|
|
118
|
+
* @param options Additional options.
|
|
119
|
+
* @param options.initialState If "true" the value will be read
|
|
120
|
+
* from the initial state instead of the current one.
|
|
121
|
+
* @param options.initialValue If the value read from the "path" is
|
|
122
|
+
* "undefined", this "initialValue" will be returned instead. In such case
|
|
123
|
+
* "initialValue" will also be written to the "path" of the current global
|
|
124
|
+
* state (no matter "initialState" flag), if "undefined" is stored there.
|
|
125
|
+
* @return Retrieved value.
|
|
126
|
+
*/
|
|
127
|
+
|
|
128
|
+
// .get() without arguments just falls back to .getEntireState().
|
|
129
|
+
// This variant attempts to automatically resolve and check the type of value
|
|
130
|
+
// at the given path, as precise as the actual state and path types permit.
|
|
131
|
+
// If the automatic path resolution is not possible, the ValueT fallsback
|
|
132
|
+
// to `never` (or to `undefined` in some cases), effectively forbidding
|
|
133
|
+
// to use this .get() variant.
|
|
134
|
+
// This variant is not callable by default (without generic arguments),
|
|
135
|
+
// otherwise it allows to set the correct ValueT directly.
|
|
136
|
+
get(path, opts) {
|
|
137
|
+
if (isNil(path)) {
|
|
138
|
+
const res = this.getEntireState(opts);
|
|
139
|
+
return res;
|
|
140
|
+
}
|
|
141
|
+
const state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
|
|
142
|
+
let res = get(state, path);
|
|
143
|
+
if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return res;
|
|
144
|
+
const iv = opts.initialValue;
|
|
145
|
+
res = isFunction(iv) ? iv() : iv;
|
|
146
|
+
if (!(opts !== null && opts !== void 0 && opts.initialState) || this.get(path) === undefined) {
|
|
147
|
+
this.set(path, res);
|
|
148
|
+
}
|
|
149
|
+
return res;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Writes the `value` to given global state `path`.
|
|
154
|
+
* @param path Dot-delimitered state path. If not given, entire
|
|
155
|
+
* global state content is replaced by the `value`.
|
|
156
|
+
* @param value The value.
|
|
157
|
+
* @return Given `value` itself.
|
|
158
|
+
*/
|
|
159
|
+
|
|
160
|
+
// This variant attempts automatic value type resolution & checking.
|
|
161
|
+
// This variant is disabled by default, otherwise allows to give
|
|
162
|
+
// expected value type explicitly.
|
|
163
|
+
set(path, value) {
|
|
164
|
+
if (isNil(path)) return this.setEntireState(value);
|
|
165
|
+
if (value !== this.get(path)) {
|
|
166
|
+
const root = {
|
|
167
|
+
state: _classPrivateFieldGet(this, _currentState)
|
|
168
|
+
};
|
|
169
|
+
let segIdx = 0;
|
|
170
|
+
let pos = root;
|
|
171
|
+
const pathSegments = toPath(`state.${path}`);
|
|
172
|
+
for (; segIdx < pathSegments.length - 1; segIdx += 1) {
|
|
173
|
+
const seg = pathSegments[segIdx];
|
|
174
|
+
const next = pos[seg];
|
|
175
|
+
if (Array.isArray(next)) pos[seg] = [...next];else if (isObject(next)) pos[seg] = {
|
|
176
|
+
...next
|
|
177
|
+
};else {
|
|
178
|
+
// We arrived to a state sub-segment, where the remaining part of
|
|
179
|
+
// the update path does not exist yet. We rely on lodash's set()
|
|
180
|
+
// function to create the remaining path, and set the value.
|
|
181
|
+
set(pos, pathSegments.slice(segIdx), value);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
pos = pos[seg];
|
|
185
|
+
}
|
|
186
|
+
if (segIdx === pathSegments.length - 1) {
|
|
187
|
+
pos[pathSegments[segIdx]] = value;
|
|
188
|
+
}
|
|
189
|
+
_classPrivateFieldSet(this, _currentState, root.state);
|
|
190
|
+
this.notifyStateUpdate(path, value);
|
|
191
|
+
}
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Unsubscribes `callback` from watching state updates; no operation if
|
|
197
|
+
* `callback` is not subscribed to the state updates.
|
|
198
|
+
* @param callback
|
|
199
|
+
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
200
|
+
* watching functionality is intended for client-side (non-SSR) only.
|
|
201
|
+
*/
|
|
202
|
+
unWatch(callback) {
|
|
203
|
+
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
204
|
+
const watchers = _classPrivateFieldGet(this, _watchers);
|
|
205
|
+
const pos = watchers.indexOf(callback);
|
|
206
|
+
if (pos >= 0) {
|
|
207
|
+
watchers[pos] = watchers[watchers.length - 1];
|
|
208
|
+
watchers.pop();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Subscribes `callback` to watch state updates; no operation if
|
|
214
|
+
* `callback` is already subscribed to this state instance.
|
|
215
|
+
* @param callback It will be called without any arguments every
|
|
216
|
+
* time the state content changes (note, howhever, separate state updates can
|
|
217
|
+
* be applied to the state at once, and watching callbacks will be called once
|
|
218
|
+
* after such bulk update).
|
|
219
|
+
* @throws if {@link SsrContext} is attached to the state instance: the state
|
|
220
|
+
* watching functionality is intended for client-side (non-SSR) only.
|
|
221
|
+
*/
|
|
222
|
+
watch(callback) {
|
|
223
|
+
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
224
|
+
const watchers = _classPrivateFieldGet(this, _watchers);
|
|
225
|
+
if (watchers.indexOf(callback) < 0) {
|
|
226
|
+
watchers.push(callback);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=GlobalState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GlobalState.js","names":["cloneDeep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_initialState","WeakMap","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","writable","value","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","path","p","setTimeout","watchers","i","length","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeep(value));\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | false = false, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | false = false, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;AAAA,SACEA,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAMEC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,aAAA,oBAAAC,OAAA;AAAA,IAAAC,SAAA,oBAAAD,OAAA;AAAA,IAAAE,eAAA,oBAAAF,OAAA;AAAA,IAAAG,aAAA,oBAAAH,OAAA;AAO1E,eAAe,MAAMI,WAAW,CAG9B;EAeA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAAAC,0BAAA,OAAAT,aAAA;MAAAU,QAAA;MAAAC,KAAA;IAAA;IAlBF;IACA;IACA;IACA;IAAAF,0BAAA,OAAAP,SAAA;MAAAQ,QAAA;MAAAC,KAAA,EACyB;IAAE;IAAAF,0BAAA,OAAAN,eAAA;MAAAO,QAAA;MAAAC,KAAA;IAAA;IAAAF,0BAAA,OAAAL,aAAA;MAAAM,QAAA;MAAAC,KAAA;IAAA;IAezBC,qBAAA,KAAI,EAAAR,aAAA,EAAiBG,YAAY;IACjCK,qBAAA,KAAI,EAAAZ,aAAA,EAAiBO,YAAY;IAEjC,IAAIC,UAAU,EAAE;MACd;MACAA,UAAU,CAACK,KAAK,GAAG,KA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ACd;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;EACEqC,OAAOA,CAACC,QAAmB,EAAE;IAC3B,IAAI,IAAI,CAACzC,UAAU,EAAE,MAAM,IAAI0C,KAAK,CAACnD,gBAAgB,CAAC;IAEtD,MAAMoC,QAAQ,GAAAnB,qBAAA,CAAG,IAAI,EAAAd,SAAA,CAAU;IAC/B,MAAMuC,GAAG,GAAGN,QAAQ,CAACgB,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIR,GAAG,IAAI,CAAC,EAAE;MACZN,QAAQ,CAACM,GAAG,CAAC,GAAGN,QAAQ,CAACA,QAAQ,CAACE,MAAM,GAAG,CAAC,CAAC;MAC7CF,QAAQ,CAACiB,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAACzC,UAAU,EAAE,MAAM,IAAI0C,KAAK,CAACnD,gBAAgB,CAAC;IAEtD,MAAMoC,QAAQ,GAAAnB,qBAAA,CAAG,IAAI,EAAAd,SAAA,CAAU;IAC/B,IAAIiC,QAAQ,CAACgB,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCd,QAAQ,CAACmB,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/* eslint-disable react/prop-types */
|
|
2
|
+
|
|
3
|
+
import { isFunction } from 'lodash';
|
|
4
|
+
import { createContext, useContext, useRef } from 'react';
|
|
5
|
+
import GlobalState from "./GlobalState";
|
|
6
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
7
|
+
const context = /*#__PURE__*/createContext(null);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Gets {@link GlobalState} instance from the context. In most cases
|
|
11
|
+
* you should use {@link useGlobalState}, and other hooks to interact with
|
|
12
|
+
* the global state, instead of accessing it directly.
|
|
13
|
+
* @return
|
|
14
|
+
*/
|
|
15
|
+
export function getGlobalState() {
|
|
16
|
+
// Here Rules of Hooks are violated because "getGlobalState()" does not follow
|
|
17
|
+
// convention that hook names should start with use... This is intentional in
|
|
18
|
+
// our case, as getGlobalState() hook is intended for advance scenarious,
|
|
19
|
+
// while the normal interaction with the global state should happen via
|
|
20
|
+
// another hook, useGlobalState().
|
|
21
|
+
/* eslint-disable react-hooks/rules-of-hooks */
|
|
22
|
+
const globalState = useContext(context);
|
|
23
|
+
/* eslint-enable react-hooks/rules-of-hooks */
|
|
24
|
+
if (!globalState) throw new Error('Missing GlobalStateProvider');
|
|
25
|
+
return globalState;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @category Hooks
|
|
30
|
+
* @desc Gets SSR context.
|
|
31
|
+
* @param throwWithoutSsrContext If `true` (default),
|
|
32
|
+
* this hook will throw if no SSR context is attached to the global state;
|
|
33
|
+
* set `false` to not throw in such case. In either case the hook will throw
|
|
34
|
+
* if the {@link <GlobalStateProvider>} (hence the state) is missing.
|
|
35
|
+
* @returns SSR context.
|
|
36
|
+
* @throws
|
|
37
|
+
* - If current component has no parent {@link <GlobalStateProvider>}
|
|
38
|
+
* in the rendered React tree.
|
|
39
|
+
* - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
|
|
40
|
+
* to the global state provided by {@link <GlobalStateProvider>}.
|
|
41
|
+
*/
|
|
42
|
+
export function getSsrContext() {
|
|
43
|
+
let throwWithoutSsrContext = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
|
|
44
|
+
const {
|
|
45
|
+
ssrContext
|
|
46
|
+
} = getGlobalState();
|
|
47
|
+
if (!ssrContext && throwWithoutSsrContext) {
|
|
48
|
+
throw new Error('No SSR context found');
|
|
49
|
+
}
|
|
50
|
+
return ssrContext;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Provides global state to its children.
|
|
54
|
+
* @param prop.children Component children, which will be provided with
|
|
55
|
+
* the global state, and rendered in place of the provider.
|
|
56
|
+
* @param prop.initialState Initial content of the global state.
|
|
57
|
+
* @param prop.ssrContext Server-side rendering (SSR) context.
|
|
58
|
+
* @param prop.stateProxy This option is useful for code
|
|
59
|
+
* splitting and SSR implementation:
|
|
60
|
+
* - If `true`, this provider instance will fetch and reuse the global state
|
|
61
|
+
* from a parent provider.
|
|
62
|
+
* - If `GlobalState` instance, it will be used by this provider.
|
|
63
|
+
* - If not given, a new `GlobalState` instance will be created and used.
|
|
64
|
+
*/
|
|
65
|
+
export default function GlobalStateProvider(_ref) {
|
|
66
|
+
let {
|
|
67
|
+
children,
|
|
68
|
+
...rest
|
|
69
|
+
} = _ref;
|
|
70
|
+
const state = useRef();
|
|
71
|
+
if (!state.current) {
|
|
72
|
+
// NOTE: The last part of condition, "&& rest.stateProxy", is needed for
|
|
73
|
+
// graceful compatibility with JavaScript - if "undefined" stateProxy value
|
|
74
|
+
// is given, we want to follow the second branch, which creates a new
|
|
75
|
+
// GlobalState with whatever intiialState given.
|
|
76
|
+
if ('stateProxy' in rest && rest.stateProxy) {
|
|
77
|
+
if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
|
|
78
|
+
} else {
|
|
79
|
+
const {
|
|
80
|
+
initialState,
|
|
81
|
+
ssrContext
|
|
82
|
+
} = rest;
|
|
83
|
+
state.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return /*#__PURE__*/_jsx(context.Provider, {
|
|
87
|
+
value: state.current,
|
|
88
|
+
children: children
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
GlobalStateProvider.defaultProps = {
|
|
92
|
+
children: undefined
|
|
93
|
+
};
|
|
94
|
+
//# sourceMappingURL=GlobalStateProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value","defaultProps"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link <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 */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n\nGlobalStateProvider.defaultProps = {\n children: undefined,\n};\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAA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C,KAC1Da,KAAK,CAACC,OAAO,GAAGF,IAAI,CAACG,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGI,IAA0C;MAE/EC,KAAK,CAACC,OAAO,GAAG,IAAIlB,WAAW,CAC7BJ,UAAU,CAACwB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAF,mBAAmB,CAACU,YAAY,GAAG;EACjCR,QAAQ,EAAEJ;AACZ,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
2
|
+
export default class SsrContext {
|
|
3
|
+
constructor(state) {
|
|
4
|
+
_defineProperty(this, "dirty", false);
|
|
5
|
+
_defineProperty(this, "pending", []);
|
|
6
|
+
this.state = state;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=SsrContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SsrContext.js","names":["SsrContext","constructor","state","_defineProperty"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAOtCC,WAAWA,CAACC,KAAc,EAAE;IAAAC,eAAA,gBANX,KAAK;IAAAA,eAAA,kBAEK,EAAE;IAK3B,IAAI,CAACD,KAAK,GAAGA,KAAK;EACpB;AACF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { default as GlobalState } from "./GlobalState";
|
|
2
|
+
export { default as GlobalStateProvider, getGlobalState, getSsrContext } from "./GlobalStateProvider";
|
|
3
|
+
export { default as SsrContext } from "./SsrContext";
|
|
4
|
+
export { default as useAsyncCollection } from "./useAsyncCollection";
|
|
5
|
+
export { default as useAsyncData, newAsyncDataEnvelope } from "./useAsyncData";
|
|
6
|
+
export { default as useGlobalState } from "./useGlobalState";
|
|
7
|
+
export { default as withGlobalStateType } from "./withGlobalStateType";
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["default","GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","useAsyncData","newAsyncDataEnvelope","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["export { default as GlobalState } from './GlobalState';\n\nexport {\n default as GlobalStateProvider,\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nexport { default as SsrContext } from './SsrContext';\n\nexport {\n type AsyncCollectionLoaderT,\n default as useAsyncCollection,\n} from './useAsyncCollection';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n default as useAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nexport {\n type SetterT,\n type UseGlobalStateResT,\n default as useGlobalState,\n} from './useGlobalState';\n\nexport { type ForceT, type ValueOrInitializerT } from './utils';\n\nexport { default as withGlobalStateType } from './withGlobalStateType';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,WAAW;AAE/B,SACED,OAAO,IAAIE,mBAAmB,EAC9BC,cAAc,EACdC,aAAa;AAGf,SAASJ,OAAO,IAAIK,UAAU;AAE9B,SAEEL,OAAO,IAAIM,kBAAkB;AAG/B,SAKEN,OAAO,IAAIO,YAAY,EACvBC,oBAAoB;AAGtB,SAGER,OAAO,IAAIS,cAAc;AAK3B,SAAST,OAAO,IAAIU,mBAAmB"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads and uses an item in an async collection.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import useAsyncData from "./useAsyncData";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Resolves and stores at the given `path` of global state elements of
|
|
9
|
+
* an asynchronous data collection. In other words, it is an auxiliar wrapper
|
|
10
|
+
* around {@link useAsyncData}, which uses a loader which resolves to different
|
|
11
|
+
* data, based on ID argument passed in, and stores data fetched for different
|
|
12
|
+
* IDs in the state.
|
|
13
|
+
* @param id ID of the collection item to load & use.
|
|
14
|
+
* @param path The global state path where entire collection should be
|
|
15
|
+
* stored.
|
|
16
|
+
* @param loader A loader function, which takes an
|
|
17
|
+
* ID of data to load, and resolves to the corresponding data.
|
|
18
|
+
* @param options Additional options.
|
|
19
|
+
* @param options.deps An array of dependencies, which trigger
|
|
20
|
+
* data reload when changed. Given dependency changes are watched shallowly
|
|
21
|
+
* (similarly to the standard React's
|
|
22
|
+
* [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
|
|
23
|
+
* @param options.noSSR If `true`, this hook won't load data during
|
|
24
|
+
* server-side rendering.
|
|
25
|
+
* @param options.garbageCollectAge The maximum age of data
|
|
26
|
+
* (in milliseconds), after which they are dropped from the state when the last
|
|
27
|
+
* component referencing them via `useAsyncData()` hook unmounts. Defaults to
|
|
28
|
+
* `maxage` option value.
|
|
29
|
+
* @param options.maxage The maximum age of
|
|
30
|
+
* data (in milliseconds) acceptable to the hook's caller. If loaded data are
|
|
31
|
+
* older than this value, `null` is returned instead. Defaults to 5 minutes.
|
|
32
|
+
* @param options.refreshAge The maximum age of data
|
|
33
|
+
* (in milliseconds), after which their refreshment will be triggered when
|
|
34
|
+
* any component referencing them via `useAsyncData()` hook (re-)renders.
|
|
35
|
+
* Defaults to `maxage` value.
|
|
36
|
+
* @return Returns an object with three fields: `data` holds the actual result of
|
|
37
|
+
* last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
|
|
38
|
+
* is a boolean flag, which is `true` if data are being loaded (the hook is
|
|
39
|
+
* waiting for `loader` function resolution); `timestamp` (in milliseconds)
|
|
40
|
+
* is Unix timestamp of related data currently loaded into the global state.
|
|
41
|
+
*
|
|
42
|
+
* Note that loaded data, if any, are stored at the given `path` of global state
|
|
43
|
+
* along with related meta-information, using slightly different state segment
|
|
44
|
+
* structure (see {@link AsyncDataEnvelope}). That segment of the global state
|
|
45
|
+
* can be accessed, and even modified using other hooks,
|
|
46
|
+
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
47
|
+
* `useAsyncData()` hooks logic.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
function useAsyncCollection(id, path, loader) {
|
|
51
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
52
|
+
const itemPath = path ? `${path}.${id}` : id;
|
|
53
|
+
return useAsyncData(itemPath, oldData => loader(id, oldData), options);
|
|
54
|
+
}
|
|
55
|
+
export default useAsyncCollection;
|
|
56
|
+
//# sourceMappingURL=useAsyncCollection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>\n >,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | false = false,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,YAAY;;AAWnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAyBA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB"}
|