@dr.pogodin/react-global-state 0.10.0-alpha.3 → 0.10.0-alpha.4
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/common/GlobalState.js.map +1 -1
- package/build/common/index.js +12 -7
- package/build/common/index.js.map +1 -1
- package/build/common/useAsyncCollection.js.map +1 -1
- package/build/common/useAsyncData.js.map +1 -1
- package/build/common/useGlobalState.js +3 -2
- package/build/common/useGlobalState.js.map +1 -1
- package/build/common/utils.js +2 -3
- package/build/common/utils.js.map +1 -1
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/index.js +18 -7
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js.map +1 -1
- package/build/module/useGlobalState.js +3 -2
- package/build/module/useGlobalState.js.map +1 -1
- package/build/module/utils.js +2 -2
- package/build/module/utils.js.map +1 -1
- package/build/types/GlobalState.d.ts +3 -3
- package/build/types/index.d.ts +24 -8
- package/build/types/useAsyncCollection.d.ts +6 -2
- package/build/types/useAsyncData.d.ts +6 -2
- package/build/types/useGlobalState.d.ts +7 -2
- package/build/types/utils.d.ts +3 -1
- package/package.json +1 -1
- package/src/GlobalState.ts +3 -2
- package/src/index.ts +57 -19
- package/src/useAsyncCollection.ts +18 -2
- package/src/useAsyncData.ts +17 -2
- package/src/useGlobalState.ts +24 -3
- package/src/utils.ts +6 -3
- package/tsconfig.json +1 -1
- package/build/common/withGlobalStateType.js +0 -42
- package/build/common/withGlobalStateType.js.map +0 -1
- package/build/module/withGlobalStateType.js +0 -35
- package/build/module/withGlobalStateType.js.map +0 -1
- package/build/types/withGlobalStateType.d.ts +0 -29
- package/src/withGlobalStateType.ts +0 -170
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | false = false,\n DataT = unknown,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAIEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAEP;EAAA,IAD3BC,WAAyB,GAAA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CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAEP;EAAA,IAD3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAEhC,OAAO;IACLG,IAAI,EAAEJ,WAAW;IACjBK,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAIA,CACjBC,IAA+B,EAC/BC,MAA+B,EAC/BC,WAAsD,EACtDC,OAAqB,EAEN;EAAA,IADfC,UAAqB,GAAAZ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,GAAG;EAE3B,IAAIa,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAInB,WAAW,CAAC,CAAC,EAAE;IAC1D;IACAoB,OAAO,CAACC,GAAG,CACR,4DAA2DT,IAAI,IAAI,EAAG,GACzE,CAAC;IACD;EACF;;EACA,MAAMH,WAAW,GAAGO,UAAU,GAAGpB,IAAI,CAAC,CAAC;EACvC,MAAM0B,eA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;IAC/BlD,SAAS,CAAC,MAAM;MAAE;MAChB,IAAI,CAACgD,aAAa,IAAIE,IAAI,CAACvC,MAAM,EAAEM,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;IAC1E,CAAC,EAAE8B,IAAI,CAAC,CAAC,CAAC;EACZ;;EAEA,MAAM,CAACC,UAAU,CAAC,GAAG9C,cAAc,CACjCa,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLK,IAAI,EAAEyB,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGiB,UAAU,CAACnC,SAAS,GAAG,IAAI,GAAGmC,UAAU,CAACtC,IAAI;IACzEuC,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACpC,WAAW,CAAC;IACxCC,SAAS,EAAEmC,UAAU,CAACnC;EACxB,CAAC;AACH;AAEA,eAAeoB,YAAY"}
|
|
@@ -55,8 +55,9 @@ import { isDebugMode } from "./utils";
|
|
|
55
55
|
*
|
|
56
56
|
* Also, similar to the standard React's state setters, `setValue()` is
|
|
57
57
|
* stable function: it does not change between component re-renders.
|
|
58
|
-
*/
|
|
59
|
-
|
|
58
|
+
*/ // "Enforced type overload"
|
|
59
|
+
// "Entire state overload"
|
|
60
|
+
// "State evaluation overload"
|
|
60
61
|
function useGlobalState(path, initialValue) {
|
|
61
62
|
const globalState = getGlobalState();
|
|
62
63
|
const ref = useRef();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","watcher","get","emit","cb","addListener","initialState","watch","unWatch"],"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\
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","Emitter","getGlobalState","isDebugMode","useGlobalState","path","initialValue","globalState","ref","rc","current","emitter","setter","value","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","set","watcher","get","emit","cb","addListener","initialState","watch","unWatch"],"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 LockT,\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\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<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\nexport interface UseGlobalStateI<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 | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, 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AEV,OAAO,CAACI,EAAE,CAACM,KAAK,EAAEN,EAAE,CAACG,MAAM,CAAC;AAC9B;AAEA,eAAeR,cAAc"}
|
package/build/module/utils.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// TODO: This (ForceT
|
|
2
|
-
//
|
|
1
|
+
// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
|
|
2
|
+
// lib.
|
|
3
3
|
/**
|
|
4
4
|
* Given the type of state, `StateT`, and the type of state path, `PathT`,
|
|
5
5
|
* it evaluates the type of value at that path of the state, if it can be
|
|
@@ -1 +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
|
|
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, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\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;AACA;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import SsrContext from './SsrContext';
|
|
2
|
-
import { type CallbackT, type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
2
|
+
import { type CallbackT, type ForceT, type LockT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
3
3
|
type GetOptsT<T> = {
|
|
4
4
|
initialState?: boolean;
|
|
5
5
|
initialValue?: ValueOrInitializerT<T>;
|
|
@@ -42,7 +42,7 @@ export default class GlobalState<StateT, SsrContextT extends SsrContext<StateT>
|
|
|
42
42
|
*/
|
|
43
43
|
get(): StateT;
|
|
44
44
|
get<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
|
|
45
|
-
get<Forced extends ForceT |
|
|
45
|
+
get<Forced extends ForceT | LockT = LockT, ValueT = void>(path?: null | string, opts?: GetOptsT<TypeLock<Forced, never, ValueT>>): TypeLock<Forced, void, ValueT>;
|
|
46
46
|
/**
|
|
47
47
|
* Writes the `value` to given global state `path`.
|
|
48
48
|
* @param path Dot-delimitered state path. If not given, entire
|
|
@@ -51,7 +51,7 @@ export default class GlobalState<StateT, SsrContextT extends SsrContext<StateT>
|
|
|
51
51
|
* @return Given `value` itself.
|
|
52
52
|
*/
|
|
53
53
|
set<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, value: ValueArgT): ValueResT;
|
|
54
|
-
set<Forced extends ForceT |
|
|
54
|
+
set<Forced extends ForceT | LockT = LockT, ValueT = never>(path: null | string | undefined, value: TypeLock<Forced, never, ValueT>): TypeLock<Forced, void, ValueT>;
|
|
55
55
|
/**
|
|
56
56
|
* Unsubscribes `callback` from watching state updates; no operation if
|
|
57
57
|
* `callback` is not subscribed to the state updates.
|
package/build/types/index.d.ts
CHANGED
|
@@ -1,8 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export
|
|
8
|
-
export {
|
|
1
|
+
import GlobalState from './GlobalState';
|
|
2
|
+
import GlobalStateProvider, { getGlobalState, getSsrContext } from './GlobalStateProvider';
|
|
3
|
+
import SsrContext from './SsrContext';
|
|
4
|
+
import useAsyncCollection, { type UseAsyncCollectionI } from './useAsyncCollection';
|
|
5
|
+
import useAsyncData, { type UseAsyncDataI, newAsyncDataEnvelope } from './useAsyncData';
|
|
6
|
+
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
7
|
+
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
8
|
+
export type { AsyncDataEnvelopeT, AsyncDataLoaderT, UseAsyncDataOptionsT, UseAsyncDataResT, } from './useAsyncData';
|
|
9
|
+
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
10
|
+
export type { ForceT, ValueOrInitializerT } from './utils';
|
|
11
|
+
export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState, };
|
|
12
|
+
export interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
|
|
13
|
+
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
14
|
+
getSsrContext: typeof getSsrContext<SsrContextT>;
|
|
15
|
+
GlobalState: typeof GlobalState<StateT, SsrContextT>;
|
|
16
|
+
GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;
|
|
17
|
+
newAsyncDataEnvelope: typeof newAsyncDataEnvelope;
|
|
18
|
+
SsrContext: typeof SsrContext<StateT>;
|
|
19
|
+
useAsyncCollection: UseAsyncCollectionI<StateT>;
|
|
20
|
+
useAsyncData: UseAsyncDataI<StateT>;
|
|
21
|
+
useGlobalState: UseGlobalStateI<StateT>;
|
|
22
|
+
}
|
|
23
|
+
declare const _default: API<unknown, SsrContext<unknown>>;
|
|
24
|
+
export default _default;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Loads and uses an item in an async collection.
|
|
3
3
|
*/
|
|
4
4
|
import { type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
|
|
5
|
-
import { type ForceT, type TypeLock } from './utils';
|
|
5
|
+
import { type ForceT, type LockT, type TypeLock } from './utils';
|
|
6
6
|
export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT) => DataT | Promise<DataT>;
|
|
7
7
|
/**
|
|
8
8
|
* Resolves and stores at the given `path` of global state elements of
|
|
@@ -47,5 +47,9 @@ export type AsyncCollectionLoaderT<DataT> = (id: string, oldData: null | DataT)
|
|
|
47
47
|
* `useAsyncData()` hooks logic.
|
|
48
48
|
*/
|
|
49
49
|
declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
50
|
-
declare function useAsyncCollection<Forced extends ForceT |
|
|
50
|
+
declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
51
51
|
export default useAsyncCollection;
|
|
52
|
+
export interface UseAsyncCollectionI<StateT> {
|
|
53
|
+
<PathT extends null | string | undefined, IdT extends string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
54
|
+
<Forced extends ForceT | LockT = LockT, DataT = unknown>(id: string, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
55
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Loads and uses async data into the GlobalState path.
|
|
3
3
|
*/
|
|
4
|
-
import { type ForceT, type TypeLock, type ValueAtPathT } from './utils';
|
|
4
|
+
import { type ForceT, type LockT, type TypeLock, type ValueAtPathT } from './utils';
|
|
5
5
|
export type AsyncDataLoaderT<DataT> = (oldData: null | DataT) => DataT | Promise<DataT>;
|
|
6
6
|
export type AsyncDataEnvelopeT<DataT> = {
|
|
7
7
|
data: null | DataT;
|
|
@@ -71,5 +71,9 @@ export type UseAsyncDataResT<DataT> = {
|
|
|
71
71
|
*/
|
|
72
72
|
export type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined> = ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown> ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null> : void;
|
|
73
73
|
declare function useAsyncData<StateT, PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
74
|
-
declare function useAsyncData<Forced extends ForceT |
|
|
74
|
+
declare function useAsyncData<Forced extends ForceT | LockT = LockT, DataT = void>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
75
75
|
export default useAsyncData;
|
|
76
|
+
export interface UseAsyncDataI<StateT> {
|
|
77
|
+
<PathT extends null | string | undefined>(path: PathT, loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
78
|
+
<Forced extends ForceT | LockT = LockT, DataT = unknown>(path: null | string | undefined, loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
79
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { type ForceT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
2
|
+
import { type ForceT, type LockT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
|
|
3
3
|
export type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;
|
|
4
4
|
export type UseGlobalStateResT<T> = [T, SetterT<T>];
|
|
5
5
|
/**
|
|
@@ -52,7 +52,12 @@ export type UseGlobalStateResT<T> = [T, SetterT<T>];
|
|
|
52
52
|
* Also, similar to the standard React's state setters, `setValue()` is
|
|
53
53
|
* stable function: it does not change between component re-renders.
|
|
54
54
|
*/
|
|
55
|
+
declare function useGlobalState<Forced extends ForceT | LockT = LockT, ValueT = void>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
55
56
|
declare function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
|
|
56
|
-
declare function useGlobalState<Forced extends ForceT | false = false, ValueT = unknown>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
57
57
|
declare function useGlobalState<StateT, PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
58
58
|
export default useGlobalState;
|
|
59
|
+
export interface UseGlobalStateI<StateT> {
|
|
60
|
+
(): UseGlobalStateResT<StateT>;
|
|
61
|
+
<PathT extends null | string | undefined>(path: PathT, initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
62
|
+
<Forced extends ForceT | LockT = LockT, ValueT = unknown>(path: null | string | undefined, initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
63
|
+
}
|
package/build/types/utils.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { type GetFieldType } from 'lodash';
|
|
2
2
|
export type CallbackT = () => void;
|
|
3
3
|
declare const force: unique symbol;
|
|
4
|
+
declare const lock: unique symbol;
|
|
4
5
|
export type ForceT = typeof force;
|
|
5
|
-
export type
|
|
6
|
+
export type LockT = typeof lock;
|
|
7
|
+
export type TypeLock<Unlocked extends ForceT | LockT, LockedT extends never | void, UnlockedT> = Unlocked extends ForceT ? UnlockedT : LockedT;
|
|
6
8
|
/**
|
|
7
9
|
* Given the type of state, `StateT`, and the type of state path, `PathT`,
|
|
8
10
|
* it evaluates the type of value at that path of the state, if it can be
|
package/package.json
CHANGED
package/src/GlobalState.ts
CHANGED
|
@@ -13,6 +13,7 @@ import SsrContext from './SsrContext';
|
|
|
13
13
|
import {
|
|
14
14
|
type CallbackT,
|
|
15
15
|
type ForceT,
|
|
16
|
+
type LockT,
|
|
16
17
|
type TypeLock,
|
|
17
18
|
type ValueAtPathT,
|
|
18
19
|
type ValueOrInitializerT,
|
|
@@ -162,7 +163,7 @@ export default class GlobalState<
|
|
|
162
163
|
|
|
163
164
|
// This variant is not callable by default (without generic arguments),
|
|
164
165
|
// otherwise it allows to set the correct ValueT directly.
|
|
165
|
-
get<Forced extends ForceT |
|
|
166
|
+
get<Forced extends ForceT | LockT = LockT, ValueT = void>(
|
|
166
167
|
path?: null | string,
|
|
167
168
|
opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,
|
|
168
169
|
): TypeLock<Forced, void, ValueT>;
|
|
@@ -205,7 +206,7 @@ export default class GlobalState<
|
|
|
205
206
|
|
|
206
207
|
// This variant is disabled by default, otherwise allows to give
|
|
207
208
|
// expected value type explicitly.
|
|
208
|
-
set<Forced extends ForceT |
|
|
209
|
+
set<Forced extends ForceT | LockT = LockT, ValueT = never>(
|
|
209
210
|
path: null | string | undefined,
|
|
210
211
|
value: TypeLock<Forced, never, ValueT>,
|
|
211
212
|
): TypeLock<Forced, void, ValueT>;
|
package/src/index.ts
CHANGED
|
@@ -1,33 +1,71 @@
|
|
|
1
|
-
|
|
1
|
+
import GlobalState from './GlobalState';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
default as GlobalStateProvider,
|
|
3
|
+
import GlobalStateProvider, {
|
|
5
4
|
getGlobalState,
|
|
6
5
|
getSsrContext,
|
|
7
6
|
} from './GlobalStateProvider';
|
|
8
7
|
|
|
9
|
-
|
|
8
|
+
import SsrContext from './SsrContext';
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
type
|
|
13
|
-
default as useAsyncCollection,
|
|
10
|
+
import useAsyncCollection, {
|
|
11
|
+
type UseAsyncCollectionI,
|
|
14
12
|
} from './useAsyncCollection';
|
|
15
13
|
|
|
16
|
-
|
|
17
|
-
type
|
|
18
|
-
type AsyncDataLoaderT,
|
|
19
|
-
type UseAsyncDataOptionsT,
|
|
20
|
-
type UseAsyncDataResT,
|
|
21
|
-
default as useAsyncData,
|
|
14
|
+
import useAsyncData, {
|
|
15
|
+
type UseAsyncDataI,
|
|
22
16
|
newAsyncDataEnvelope,
|
|
23
17
|
} from './useAsyncData';
|
|
24
18
|
|
|
19
|
+
import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
20
|
+
|
|
21
|
+
export type { AsyncCollectionLoaderT } from './useAsyncCollection';
|
|
22
|
+
|
|
23
|
+
export type {
|
|
24
|
+
AsyncDataEnvelopeT,
|
|
25
|
+
AsyncDataLoaderT,
|
|
26
|
+
UseAsyncDataOptionsT,
|
|
27
|
+
UseAsyncDataResT,
|
|
28
|
+
} from './useAsyncData';
|
|
29
|
+
|
|
30
|
+
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
31
|
+
|
|
32
|
+
export type { ForceT, ValueOrInitializerT } from './utils';
|
|
33
|
+
|
|
25
34
|
export {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
35
|
+
getGlobalState,
|
|
36
|
+
getSsrContext,
|
|
37
|
+
GlobalState,
|
|
38
|
+
GlobalStateProvider,
|
|
39
|
+
newAsyncDataEnvelope,
|
|
40
|
+
SsrContext,
|
|
41
|
+
useAsyncCollection,
|
|
42
|
+
useAsyncData,
|
|
43
|
+
useGlobalState,
|
|
44
|
+
};
|
|
30
45
|
|
|
31
|
-
export
|
|
46
|
+
export interface API<
|
|
47
|
+
StateT,
|
|
48
|
+
SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,
|
|
49
|
+
> {
|
|
50
|
+
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
51
|
+
getSsrContext: typeof getSsrContext<SsrContextT>,
|
|
52
|
+
GlobalState: typeof GlobalState<StateT, SsrContextT>,
|
|
53
|
+
GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,
|
|
54
|
+
newAsyncDataEnvelope: typeof newAsyncDataEnvelope,
|
|
55
|
+
SsrContext: typeof SsrContext<StateT>,
|
|
56
|
+
useAsyncCollection: UseAsyncCollectionI<StateT>,
|
|
57
|
+
useAsyncData: UseAsyncDataI<StateT>,
|
|
58
|
+
useGlobalState: UseGlobalStateI<StateT>,
|
|
59
|
+
}
|
|
32
60
|
|
|
33
|
-
export
|
|
61
|
+
export default {
|
|
62
|
+
getGlobalState,
|
|
63
|
+
getSsrContext,
|
|
64
|
+
GlobalState,
|
|
65
|
+
GlobalStateProvider,
|
|
66
|
+
newAsyncDataEnvelope,
|
|
67
|
+
SsrContext,
|
|
68
|
+
useAsyncCollection,
|
|
69
|
+
useAsyncData,
|
|
70
|
+
useGlobalState,
|
|
71
|
+
} as API<unknown>;
|
|
@@ -8,7 +8,7 @@ import useAsyncData, {
|
|
|
8
8
|
type UseAsyncDataResT,
|
|
9
9
|
} from './useAsyncData';
|
|
10
10
|
|
|
11
|
-
import { type ForceT, type TypeLock } from './utils';
|
|
11
|
+
import { type ForceT, type LockT, type TypeLock } from './utils';
|
|
12
12
|
|
|
13
13
|
export type AsyncCollectionLoaderT<DataT> =
|
|
14
14
|
(id: string, oldData: null | DataT) => DataT | Promise<DataT>;
|
|
@@ -70,7 +70,7 @@ function useAsyncCollection<
|
|
|
70
70
|
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
71
71
|
|
|
72
72
|
function useAsyncCollection<
|
|
73
|
-
Forced extends ForceT |
|
|
73
|
+
Forced extends ForceT | LockT = LockT,
|
|
74
74
|
DataT = unknown,
|
|
75
75
|
>(
|
|
76
76
|
id: string,
|
|
@@ -94,3 +94,19 @@ function useAsyncCollection<DataT>(
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
export default useAsyncCollection;
|
|
97
|
+
|
|
98
|
+
export interface UseAsyncCollectionI<StateT> {
|
|
99
|
+
<PathT extends null | string | undefined, IdT extends string>(
|
|
100
|
+
id: IdT,
|
|
101
|
+
path: PathT,
|
|
102
|
+
loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,
|
|
103
|
+
options?: UseAsyncDataOptionsT,
|
|
104
|
+
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
|
|
105
|
+
|
|
106
|
+
<Forced extends ForceT | LockT = LockT, DataT = unknown>(
|
|
107
|
+
id: string,
|
|
108
|
+
path: null | string | undefined,
|
|
109
|
+
loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,
|
|
110
|
+
options?: UseAsyncDataOptionsT,
|
|
111
|
+
): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
112
|
+
}
|
package/src/useAsyncData.ts
CHANGED
|
@@ -13,6 +13,7 @@ import useGlobalState from './useGlobalState';
|
|
|
13
13
|
|
|
14
14
|
import {
|
|
15
15
|
type ForceT,
|
|
16
|
+
type LockT,
|
|
16
17
|
type TypeLock,
|
|
17
18
|
type ValueAtPathT,
|
|
18
19
|
isDebugMode,
|
|
@@ -181,8 +182,8 @@ function useAsyncData<
|
|
|
181
182
|
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
182
183
|
|
|
183
184
|
function useAsyncData<
|
|
184
|
-
Forced extends ForceT |
|
|
185
|
-
DataT =
|
|
185
|
+
Forced extends ForceT | LockT = LockT,
|
|
186
|
+
DataT = void,
|
|
186
187
|
>(
|
|
187
188
|
path: null | string | undefined,
|
|
188
189
|
loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,
|
|
@@ -293,3 +294,17 @@ function useAsyncData<DataT>(
|
|
|
293
294
|
}
|
|
294
295
|
|
|
295
296
|
export default useAsyncData;
|
|
297
|
+
|
|
298
|
+
export interface UseAsyncDataI<StateT> {
|
|
299
|
+
<PathT extends null | string | undefined>(
|
|
300
|
+
path: PathT,
|
|
301
|
+
loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,
|
|
302
|
+
options?: UseAsyncDataOptionsT,
|
|
303
|
+
): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;
|
|
304
|
+
|
|
305
|
+
<Forced extends ForceT | LockT = LockT, DataT = unknown>(
|
|
306
|
+
path: null | string | undefined,
|
|
307
|
+
loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,
|
|
308
|
+
options?: UseAsyncDataOptionsT,
|
|
309
|
+
): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
|
|
310
|
+
}
|
package/src/useGlobalState.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { getGlobalState } from './GlobalStateProvider';
|
|
|
11
11
|
import {
|
|
12
12
|
type CallbackT,
|
|
13
13
|
type ForceT,
|
|
14
|
+
type LockT,
|
|
14
15
|
type TypeLock,
|
|
15
16
|
type ValueAtPathT,
|
|
16
17
|
type ValueOrInitializerT,
|
|
@@ -81,13 +82,19 @@ export type UseGlobalStateResT<T> = [T, SetterT<T>];
|
|
|
81
82
|
* stable function: it does not change between component re-renders.
|
|
82
83
|
*/
|
|
83
84
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
// "Enforced type overload"
|
|
86
|
+
function useGlobalState<
|
|
87
|
+
Forced extends ForceT | LockT = LockT,
|
|
88
|
+
ValueT = void,
|
|
89
|
+
>(
|
|
87
90
|
path: null | string | undefined,
|
|
88
91
|
initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,
|
|
89
92
|
): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
90
93
|
|
|
94
|
+
// "Entire state overload"
|
|
95
|
+
function useGlobalState<StateT>(): UseGlobalStateResT<StateT>;
|
|
96
|
+
|
|
97
|
+
// "State evaluation overload"
|
|
91
98
|
function useGlobalState<
|
|
92
99
|
StateT,
|
|
93
100
|
PathT extends null | string | undefined,
|
|
@@ -154,3 +161,17 @@ function useGlobalState(
|
|
|
154
161
|
}
|
|
155
162
|
|
|
156
163
|
export default useGlobalState;
|
|
164
|
+
|
|
165
|
+
export interface UseGlobalStateI<StateT> {
|
|
166
|
+
(): UseGlobalStateResT<StateT>;
|
|
167
|
+
|
|
168
|
+
<PathT extends null | string | undefined>(
|
|
169
|
+
path: PathT,
|
|
170
|
+
initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>
|
|
171
|
+
): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;
|
|
172
|
+
|
|
173
|
+
<Forced extends ForceT | LockT = LockT, ValueT = unknown>(
|
|
174
|
+
path: null | string | undefined,
|
|
175
|
+
initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,
|
|
176
|
+
): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;
|
|
177
|
+
}
|
package/src/utils.ts
CHANGED
|
@@ -2,14 +2,17 @@ import { type GetFieldType } from 'lodash';
|
|
|
2
2
|
|
|
3
3
|
export type CallbackT = () => void;
|
|
4
4
|
|
|
5
|
-
// TODO: This (ForceT
|
|
5
|
+
// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
|
|
6
|
+
// lib.
|
|
6
7
|
|
|
7
|
-
// This type is used to "unlocked" special generic overrides around the library.
|
|
8
8
|
declare const force: unique symbol;
|
|
9
|
+
declare const lock: unique symbol;
|
|
10
|
+
|
|
9
11
|
export type ForceT = typeof force;
|
|
12
|
+
export type LockT = typeof lock;
|
|
10
13
|
|
|
11
14
|
export type TypeLock<
|
|
12
|
-
Unlocked extends ForceT |
|
|
15
|
+
Unlocked extends ForceT | LockT,
|
|
13
16
|
LockedT extends never | void,
|
|
14
17
|
UnlockedT,
|
|
15
18
|
> = Unlocked extends ForceT ? UnlockedT : LockedT;
|
package/tsconfig.json
CHANGED