@dr.pogodin/react-global-state 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/build/{code → logic}/GlobalState.js +43 -52
- package/build/logic/GlobalState.js.map +1 -0
- package/build/logic/GlobalStateProvider.js +102 -0
- package/build/logic/GlobalStateProvider.js.map +1 -0
- package/build/logic/SsrContext.js +8 -0
- package/build/logic/SsrContext.js.map +1 -0
- package/build/{code → logic}/index.js +5 -5
- package/build/logic/index.js.map +1 -0
- package/build/{code → logic}/useAsyncCollection.js +88 -83
- package/build/logic/useAsyncCollection.js.map +1 -0
- package/build/{code → logic}/useAsyncData.js +175 -79
- package/build/logic/useAsyncData.js.map +1 -0
- package/build/{code → logic}/useGlobalState.js +8 -10
- package/build/logic/useGlobalState.js.map +1 -0
- package/build/{code → logic}/utils.js +8 -19
- package/build/logic/utils.js.map +1 -0
- package/build/types/GlobalStateProvider.d.ts +14 -16
- package/build/types/index.d.ts +4 -4
- package/build/types/utils.d.ts +2 -14
- package/package.json +29 -26
- package/build/code/GlobalState.js.map +0 -1
- package/build/code/GlobalStateProvider.js +0 -90
- package/build/code/GlobalStateProvider.js.map +0 -1
- package/build/code/SsrContext.js +0 -9
- package/build/code/SsrContext.js.map +0 -1
- package/build/code/index.js.map +0 -1
- package/build/code/useAsyncCollection.js.map +0 -1
- package/build/code/useAsyncData.js.map +0 -1
- package/build/code/useGlobalState.js.map +0 -1
- package/build/code/utils.js.map +0 -1
- package/eslint.config.mjs +0 -19
- package/tsconfig.json +0 -21
- package/tsconfig.types.json +0 -14
- package/tstyche.json +0 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["state2"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport type SsrContext from './SsrContext';\n\nimport useGlobalState from './useGlobalState';\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => Promise<void> | void;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: DataT | null;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\nexport function loadAsyncData<\n StateT,\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\nexport function loadAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function loadAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${globalThis.crypto.randomUUID()}`,\n): Promise<void> | void {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const controller = new AbortController();\n globalState.setAsyncDataAbortCallback(operationId, () => {\n controller.abort();\n });\n\n const dataOrPromise = loader(definedOld.data, {\n abortSignal: controller.signal,\n oldDataTimestamp: definedOld.timestamp,\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // NOTE: These heap fields are necessary to make reload() and set() stable\n // functions.\n globalState: GlobalState<unknown>;\n loader: AsyncDataLoaderT<DataT>;\n path: null | string | undefined;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = useGlobalStateObject();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({\n globalState,\n loader,\n path,\n });\n\n useEffect(() => {\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n });\n\n // NOTE: State inititalizer function here helps to avoid ESLint warnings\n // about accessing references during the render.\n const [stable] = useState(() => ({\n reload: (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): Promise<void> | void => {\n const localLoader = customLoader ?? heap.loader;\n\n return loadAsyncData<ForceT, DataT>(\n heap.path,\n localLoader,\n heap.globalState,\n );\n },\n set: (data: DataT | null) => {\n setState(data, heap.path, heap.globalState);\n },\n }));\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n path,\n loader,\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n `S${globalThis.crypto.randomUUID()}`,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => {\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n\n void loadAsyncData<ForceT, DataT>(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n const [stale, setStale] = useState<boolean>(\n () => maxage < Date.now() - localState.timestamp,\n );\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const nowStale = maxage < Date.now() - localState.timestamp;\n const id = stale === nowStale ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n return {\n data: stale ? null : localState.data,\n loading: !!localState.operationId,\n reload: stable.reload,\n set: stable.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoadAsyncDataI<StateT> {\n <\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n >(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";AAAA;AACA;AACA;;AAEA,SAAS,SAAS,EAAE,MAAM,EAAE,QAAQ,QAAQ,OAAO;AAEnD,SAAS,MAAM,QAAQ,sBAAsB;AAAC,SAGrC,oBAAoB;AAAA,OAItB,cAAc;AAAA,SAMnB,eAAe,EACf,WAAW;AAGb,OAAO,MAAM,cAAc,GAAG,CAAC,GAAG,MAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAoBA,OAAO,SAAS,oBAAoB,CAClC,WAAyB,GAAG,IAAI,EAChC;EAAE,OAAO,GAAG,CAAC;EAAE,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACL,IAAI,EA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,GAAG,UAAU,UAAU;MAC3D,WAAW,KAAK,KAAK,QAEnB,GAFS,IAET,GAFqC,qBAAqB,CAAC;QAC3D,QAAQ,CAAC,QAAQ,CAAC;MAAA,CACnB,CAAC;MAAC,OAEI;QACL,IAAI,EAAE,KAAK,IAAI;UAAE,oBAAoB,CAAC,EAAE,CAAC;QAAA;MAAC,CAC3C;IAAA,CACF;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EATD,SAAS,CAAC,GAST,CAAC;EAGM,iBAAK,GAAL,IAA8B,GAAf,UAAU,KAAK;EAC3B,aAAC,CAAC,UAAU,YAAY;EAAA;EAAA;IAF5B;MAAA,MACC,GAA8B;MAAA,SAC3B,GAAwB;MAAA,QACzB,MAAM,OAAO;MAAA,KAChB,MAAM,IAAI;MAAA,WACJ,UAAU;IACvB,CAAC;IAAA;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OANM,GAMN;AAAA;AAGH,SAAS,YAAY;;AAErB;;AAuBA","ignoreList":[]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
|
4
4
|
import { Emitter } from '@dr.pogodin/js-utils';
|
|
5
|
-
import {
|
|
5
|
+
import { useGlobalStateObject } from "./GlobalStateProvider.js";
|
|
6
6
|
import { cloneDeepForLog, isDebugMode } from "./utils.js";
|
|
7
7
|
/**
|
|
8
8
|
* The primary hook for interacting with the global state, modeled after
|
|
@@ -65,8 +65,7 @@ initialValue
|
|
|
65
65
|
// TODO: Revise it later!
|
|
66
66
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
67
67
|
) {
|
|
68
|
-
|
|
69
|
-
const globalState = getGlobalState();
|
|
68
|
+
const globalState = useGlobalStateObject();
|
|
70
69
|
const ref = useRef(null);
|
|
71
70
|
const [stable] = useState(() => {
|
|
72
71
|
const emitter = new Emitter();
|
|
@@ -75,10 +74,9 @@ initialValue
|
|
|
75
74
|
if (!rc) throw Error('Internal error');
|
|
76
75
|
const newState = typeof value === 'function' ? value(rc.globalState.get(rc.path)) : value;
|
|
77
76
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
78
|
-
var _rc$path, _rc$path2;
|
|
79
77
|
/* eslint-disable no-console */
|
|
80
|
-
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${
|
|
81
|
-
console.log('New value:', cloneDeepForLog(newState,
|
|
78
|
+
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path ?? ''}`);
|
|
79
|
+
console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));
|
|
82
80
|
console.groupEnd();
|
|
83
81
|
/* eslint-enable no-console */
|
|
84
82
|
}
|
|
@@ -102,16 +100,16 @@ initialValue
|
|
|
102
100
|
subscribe
|
|
103
101
|
};
|
|
104
102
|
});
|
|
105
|
-
const
|
|
103
|
+
const value_0 = useSyncExternalStore(stable.subscribe, () => globalState.get(path, {
|
|
106
104
|
initialValue
|
|
107
105
|
}), () => globalState.get(path, {
|
|
108
106
|
initialState: true,
|
|
109
107
|
initialValue
|
|
110
108
|
}));
|
|
111
|
-
|
|
109
|
+
ref.current ??= {
|
|
112
110
|
globalState,
|
|
113
111
|
path,
|
|
114
|
-
prevValue:
|
|
112
|
+
prevValue: value_0
|
|
115
113
|
};
|
|
116
114
|
useEffect(() => {
|
|
117
115
|
ref.current = {
|
|
@@ -132,7 +130,7 @@ initialValue
|
|
|
132
130
|
globalState.unWatch(watcher);
|
|
133
131
|
};
|
|
134
132
|
}, [globalState, stable.emitter, path]);
|
|
135
|
-
return [
|
|
133
|
+
return [value_0, stable.setter];
|
|
136
134
|
}
|
|
137
135
|
export default useGlobalState;
|
|
138
136
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["value"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>,\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = useGlobalStateObject();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = typeof value === 'function'\n ? (value as (x: unknown) => unknown)(\n rc.globalState.get<ForceT, unknown>(rc.path),\n ) : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAGE,SAAS,EACT,MAAM,EACN,QAAQ,EACR,oBAAoB,QACf,OAAO;AAEd,SAAS,OAAO,QAAQ,sBAAsB;AAAC,SAGtC,oBAAoB;AAAA,SAQ3B,eAAe,EACf,WAAW;AAqBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AASA;AAGA;AAkBA,SAAS,cAAc,CACrB,IAAoB;AACpB;AACA;AACA;;AAEA;AACA;AAAA,EACyB;EACzB,MAAM,WAAW,GAAG,oBAAoB,CAAC,CAAC;EAE1C,MAAM,GAAG,GAAG,MAAM,CAAW,IAAI,CAAC;EAElC,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAU,MAAM;IACvC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,CAAC;IAC7B,MAAM,MAAM,GAAI,KAAc,IAAK;MACjC,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO;MACtB,IAAI,CAAC,EAAE,EAAE,MAAM,KAAK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AW;MACX,IAAI;MACJ,SAAS,EAAE,GAAG,CAAC,OAAO,CAAE;IAC1B,CAAC;IAED,MAAM,OAAO,GAAG,MAAM;MACpB,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAkB,IAAI,CAAC;MACxD,IAAI,GAAG,CAAC,OAAO,CAAE,SAAS,KAAK,SAAS,EAAE;QACxC,GAAG,CAAC,OAAO,CAAE,SAAS,GAAG,SAAS;QAClC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;MACvB;IACF,CAAC;IAED,WAAW,CAAC,KAAK,CAAC,OAAO,CAAC;IAC1B,OAAO,CAAC,CAAC;IAET,OAAO,MAAM;MACX,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;EAEvC,OAAO,CAACA,OAAK,EAAE,MAAM,CAAC,MAAM,CAAC;AAC/B;AAEA,eAAe,cAAc;;AAE7B;AACA","ignoreList":[]}
|
|
@@ -60,24 +60,13 @@ export function cloneDeepForLog(value, key = '') {
|
|
|
60
60
|
}
|
|
61
61
|
return res;
|
|
62
62
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
return typeof x === 'string' ? x.replace(/%/g, '%0').replace(/\//g, '%1') : x.toString();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Hashes given string array. For our current needs we are fine to go with
|
|
76
|
-
* the most trivial implementation, which probably should not be called "hash"
|
|
77
|
-
* in the strict sense: we just escape each given string to not include '/'
|
|
78
|
-
* characters, and then we join all those strings using '/' as the separator.
|
|
79
|
-
*/
|
|
80
|
-
export function hash(items) {
|
|
81
|
-
return items.map(escape).join('/');
|
|
63
|
+
export function areEqual(a, b) {
|
|
64
|
+
for (const [key, value] of Object.entries(a)) {
|
|
65
|
+
if (b[key] !== value) return false;
|
|
66
|
+
}
|
|
67
|
+
for (const [key, value] of Object.entries(b)) {
|
|
68
|
+
if (a[key] !== value) return false;
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
82
71
|
}
|
|
83
72
|
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\nimport { cloneDeep } from 'lodash-es';\n\nimport type { ObjectKey } from '@dr.pogodin/js-utils';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare 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\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\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\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\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 {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\nexport function areEqual<K extends ObjectKey>(\n a: Record<K, boolean>,\n b: Record<K, boolean>,\n): boolean {\n for (const [key, value] of Object.entries(a)) {\n if (b[key as K] !== value) return false;\n }\n for (const [key, value] of Object.entries(b)) {\n if (a[key as K] !== value) return false;\n }\n return true;\n}\n"],"mappings":"AACA,SAAS,SAAS,QAAQ,WAAW;;AAMrC;AACA;;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,WAAW,GAAY;EACrC,IAAI;IACF,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,IACvC,CAAC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'./SsrContext';
|
|
4
4
|
import type { ValueOrInitializerT } from './utils';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* @return
|
|
6
|
+
* Returns the GlobalState object from the context. In most cases you should use
|
|
7
|
+
* other hooks, like useGlobalState(), etc. to interact with the global state,
|
|
8
|
+
* instead of accessing the GlobalState object directly.
|
|
10
9
|
*/
|
|
11
|
-
export declare function
|
|
10
|
+
export declare function useGlobalStateObject<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>>(): GlobalState<StateT, SsrContextT>;
|
|
12
11
|
/**
|
|
13
|
-
*
|
|
14
|
-
* @
|
|
15
|
-
*
|
|
16
|
-
* this hook will throw if
|
|
17
|
-
*
|
|
18
|
-
* if the {@link <GlobalStateProvider>} (hence the state) is missing.
|
|
12
|
+
* Returns SSR context.
|
|
13
|
+
* @param throwWithoutSsrContext - If _true_ (default), this hook will throw
|
|
14
|
+
* if no SSR context is attached to the global state; set _false_ to not throw
|
|
15
|
+
* in such case. In either case this hook will throw if the <GlobalStateProvider>
|
|
16
|
+
* (hence the global state) is missing.
|
|
19
17
|
* @returns SSR context.
|
|
20
18
|
* @throws
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
19
|
+
* - If current component has no parent <GlobalStateProvider> in the rendered
|
|
20
|
+
* React tree.
|
|
21
|
+
* - If `throwWithoutSsrContext` is _true_ (default), and there is no SSR
|
|
22
|
+
* context attached to the global state provided by <GlobalStateProvider>.
|
|
25
23
|
*/
|
|
26
|
-
export declare function
|
|
24
|
+
export declare function useSsrContext<SsrContextT extends SsrContext<unknown>>(throwWithoutSsrContext?: boolean): SsrContextT | undefined;
|
|
27
25
|
type NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {
|
|
28
26
|
initialState: ValueOrInitializerT<StateT>;
|
|
29
27
|
ssrContext?: SsrContextT;
|
package/build/types/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import GlobalState from './GlobalState';
|
|
2
|
-
import GlobalStateProvider, {
|
|
2
|
+
import GlobalStateProvider, { useGlobalStateObject, useSsrContext } from './GlobalStateProvider';
|
|
3
3
|
import SsrContext from './SsrContext';
|
|
4
4
|
import useAsyncCollection, { type UseAsyncCollectionI, type UseAsyncCollectionResT } from './useAsyncCollection';
|
|
5
5
|
import { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type LoadAsyncDataI, type UseAsyncDataI, type UseAsyncDataOptionsT, type UseAsyncDataResT, loadAsyncData, newAsyncDataEnvelope, useAsyncData } from './useAsyncData';
|
|
@@ -7,17 +7,17 @@ import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
|
|
|
7
7
|
export type { AsyncCollectionLoaderT, AsyncCollectionReloaderT, AsyncCollectionT, } from './useAsyncCollection';
|
|
8
8
|
export type { SetterT, UseGlobalStateResT } from './useGlobalState';
|
|
9
9
|
export type { ForceT, ValueOrInitializerT } from './utils';
|
|
10
|
-
export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, GlobalState, GlobalStateProvider, SsrContext, type UseAsyncCollectionI, type UseAsyncCollectionResT, type UseAsyncDataI, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateI,
|
|
10
|
+
export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, GlobalState, GlobalStateProvider, SsrContext, type UseAsyncCollectionI, type UseAsyncCollectionResT, type UseAsyncDataI, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateI, loadAsyncData, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, useGlobalStateObject, useSsrContext, };
|
|
11
11
|
interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
|
|
12
12
|
GlobalState: typeof GlobalState<StateT, SsrContextT>;
|
|
13
13
|
GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;
|
|
14
14
|
SsrContext: typeof SsrContext<StateT>;
|
|
15
|
-
getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
|
|
16
|
-
getSsrContext: typeof getSsrContext<SsrContextT>;
|
|
17
15
|
loadAsyncData: LoadAsyncDataI<StateT>;
|
|
18
16
|
newAsyncDataEnvelope: typeof newAsyncDataEnvelope;
|
|
19
17
|
useAsyncCollection: UseAsyncCollectionI<StateT>;
|
|
20
18
|
useAsyncData: UseAsyncDataI<StateT>;
|
|
21
19
|
useGlobalState: UseGlobalStateI<StateT>;
|
|
20
|
+
useGlobalStateObject: typeof useGlobalStateObject<StateT, SsrContextT>;
|
|
21
|
+
useSsrContext: typeof useSsrContext<SsrContextT>;
|
|
22
22
|
}
|
|
23
23
|
export declare function withGlobalStateType<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>>(): API<StateT, SsrContextT>;
|
package/build/types/utils.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { GetFieldType } from 'lodash';
|
|
2
|
+
import type { ObjectKey } from '@dr.pogodin/js-utils';
|
|
2
3
|
export type CallbackT = () => void;
|
|
3
4
|
export declare const force: unique symbol;
|
|
4
5
|
export declare const lock: unique symbol;
|
|
@@ -40,17 +41,4 @@ export declare function isDebugMode(): boolean;
|
|
|
40
41
|
* development versions of the app due to the logging overhead).
|
|
41
42
|
*/
|
|
42
43
|
export declare function cloneDeepForLog<T>(value: T, key?: string): T;
|
|
43
|
-
|
|
44
|
-
* Converts given value to an escaped string. For now, we are good with the most
|
|
45
|
-
* trivial escape logic:
|
|
46
|
-
* - '%' characters are replaced by '%0' code pair;
|
|
47
|
-
* - '/' characters are replaced by '%1' code pair.
|
|
48
|
-
*/
|
|
49
|
-
export declare function escape(x: number | string): string;
|
|
50
|
-
/**
|
|
51
|
-
* Hashes given string array. For our current needs we are fine to go with
|
|
52
|
-
* the most trivial implementation, which probably should not be called "hash"
|
|
53
|
-
* in the strict sense: we just escape each given string to not include '/'
|
|
54
|
-
* characters, and then we join all those strings using '/' as the separator.
|
|
55
|
-
*/
|
|
56
|
-
export declare function hash(items: Array<number | string>): string;
|
|
44
|
+
export declare function areEqual<K extends ObjectKey>(a: Record<K, boolean>, b: Record<K, boolean>): boolean;
|
package/package.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dr.pogodin/react-global-state",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "Hook-based global state for React",
|
|
5
|
-
"main": "./build/
|
|
5
|
+
"main": "./build/logic/index.js",
|
|
6
6
|
"types": "./build/types/index.d.ts",
|
|
7
7
|
"exports": {
|
|
8
8
|
"types": "./build/types/index.d.ts",
|
|
9
|
-
"default": "./build/
|
|
9
|
+
"default": "./build/logic/index.js"
|
|
10
10
|
},
|
|
11
11
|
"scripts": {
|
|
12
|
-
"build": "rimraf build && npm run build:types && npm run build:
|
|
13
|
-
"build:
|
|
12
|
+
"build": "rimraf build && npm run build:types && npm run build:logic",
|
|
13
|
+
"build:logic": "rimraf build/logic && NODE_ENV=production babel src -x .ts,.tsx --out-dir build/logic --source-maps --config-file ./babel.build.config.js",
|
|
14
14
|
"build:types": "rimraf build/types && tsc --project tsconfig.types.json",
|
|
15
15
|
"jest": "npm run jest:types && npm run jest:logic",
|
|
16
16
|
"jest:logic": "jest --config jest/config.json -w 1 --no-cache",
|
|
17
17
|
"jest:types": "tstyche",
|
|
18
|
-
"lint": "eslint --cache",
|
|
18
|
+
"lint": "eslint --cache --cache-strategy content",
|
|
19
19
|
"test": "npm run lint && npm run typecheck && npm run jest",
|
|
20
20
|
"typecheck": "tsc --noEmit"
|
|
21
21
|
},
|
|
@@ -36,43 +36,46 @@
|
|
|
36
36
|
},
|
|
37
37
|
"homepage": "https://dr.pogodin.studio/docs/react-global-state/index.html",
|
|
38
38
|
"engines": {
|
|
39
|
-
"node": ">=
|
|
39
|
+
"node": ">=22"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@
|
|
43
|
-
"@dr.pogodin/js-utils": "^0.1.6",
|
|
42
|
+
"@dr.pogodin/js-utils": "^0.2.0",
|
|
44
43
|
"@types/lodash": "^4.17.24",
|
|
45
44
|
"lodash-es": "^4.18.1"
|
|
46
45
|
},
|
|
47
46
|
"devDependencies": {
|
|
48
|
-
"@babel/cli": "^
|
|
49
|
-
"@babel/core": "^
|
|
50
|
-
"@babel/node": "^
|
|
51
|
-
"@babel/
|
|
52
|
-
"@babel/preset-
|
|
53
|
-
"@babel/preset-
|
|
54
|
-
"@babel
|
|
55
|
-
"@dr.pogodin/eslint-configs": "^0.
|
|
47
|
+
"@babel/cli": "^8.0.4",
|
|
48
|
+
"@babel/core": "^8.0.1",
|
|
49
|
+
"@babel/node": "^8.0.1",
|
|
50
|
+
"@babel/preset-env": "^8.0.2",
|
|
51
|
+
"@babel/preset-react": "^8.0.1",
|
|
52
|
+
"@babel/preset-typescript": "^8.0.1",
|
|
53
|
+
"@dr.pogodin/babel-plugin-add-import-extension": "^2.1.0",
|
|
54
|
+
"@dr.pogodin/eslint-configs": "^0.3.0",
|
|
55
|
+
"@jest/globals": "^30.4.1",
|
|
56
56
|
"@testing-library/dom": "^10.4.1",
|
|
57
57
|
"@testing-library/react": "^16.3.2",
|
|
58
58
|
"@tsconfig/recommended": "^1.0.13",
|
|
59
59
|
"@types/jest": "^30.0.0",
|
|
60
60
|
"@types/lodash-es": "^4.17.12",
|
|
61
|
+
"@types/node": "^24.13.3",
|
|
61
62
|
"@types/pretty": "^2.0.3",
|
|
62
|
-
"@types/react": "^19.2.
|
|
63
|
+
"@types/react": "^19.2.17",
|
|
63
64
|
"@types/react-dom": "^19.2.3",
|
|
64
|
-
"babel-jest": "^30.
|
|
65
|
+
"babel-jest": "^30.4.1",
|
|
65
66
|
"babel-plugin-add-import-extension": "^1.6.0",
|
|
66
67
|
"babel-plugin-module-resolver": "^5.0.3",
|
|
67
|
-
"
|
|
68
|
-
"jest
|
|
68
|
+
"babel-plugin-react-compiler": "^1.0.0",
|
|
69
|
+
"jest": "^30.4.2",
|
|
70
|
+
"jest-environment-jsdom": "^30.4.1",
|
|
69
71
|
"mockdate": "^3.0.5",
|
|
70
72
|
"rimraf": "^6.1.3",
|
|
71
|
-
"tstyche": "^7.
|
|
72
|
-
"typescript": "^
|
|
73
|
+
"tstyche": "^7.2.1",
|
|
74
|
+
"typescript": "^6.0.3"
|
|
73
75
|
},
|
|
74
76
|
"peerDependencies": {
|
|
75
|
-
"react": "^19.2.
|
|
76
|
-
"react-dom": "^19.2.
|
|
77
|
-
}
|
|
77
|
+
"react": "^19.2.7",
|
|
78
|
+
"react-dom": "^19.2.7"
|
|
79
|
+
},
|
|
80
|
+
"type": "module"
|
|
78
81
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"GlobalState.js","names":["get","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_asyncDataAbortCallbacks","WeakMap","_dependencies","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","Map","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","numAsyncDataAbortCallbacks","size","asyncDataLoadDone","opid","aborted","_classPrivateFieldGet2","delete","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","watcher","setAsyncDataAbortCallback","cb","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","includes","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\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 #asyncDataAbortCallbacks = new Map<string, () => void>();\n\n #dependencies = new Map<string, readonly unknown[]>();\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:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return this.#asyncDataAbortCallbacks.size;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks.get(opid)?.();\n this.#asyncDataAbortCallbacks.delete(opid);\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n this.#dependencies.delete(path);\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies.get(path);\n let changed = prevDeps?.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies.set(path, Object.freeze(deps));\n return changed;\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 = typeof iv === 'function' ? (iv as () => StateT)() : 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:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(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 (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks.set(opid, cb);\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 | LockT = LockT, 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 (typeof path !== 'string') {\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) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = typeof iv === 'function' ? (iv as () => ValueT)() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === 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 | LockT = LockT, 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 (typeof path !== 'string') return this.setEntireState(value as StateT);\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\n else if (typeof next === 'object') 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] as Record<string, unknown>;\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): void {\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): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SAASA,GAAG,EAAEC,GAAG,EAAEC,MAAM,QAAQ,WAAW;AAAC,SAW3CC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,wBAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,aAAA,oBAAAF,OAAA;AAAA,IAAAG,SAAA,oBAAAH,OAAA;AAAA,IAAAI,eAAA,oBAAAJ,OAAA;AAAA,IAAAK,aAAA,oBAAAL,OAAA;AAO1E,eAAe,MAAMM,WAAW,CAG9B;EAmBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAxBFC,0BAAA,OAAAX,wBAAwB,EAAG,IAAIY,GAAG,CAA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ACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAQ;IAC/B,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACtE,gBAAgB,CAAC;IAEtD,MAAMsD,QAAQ,GAAGpC,qBAAA,CAAKb,SAAS,EAAd,IAAa,CAAC;IAC/B,IAAI,CAACiD,QAAQ,CAACoB,QAAQ,CAACL,QAAQ,CAAC,EAAE;MAChCf,QAAQ,CAACqB,IAAI,CAACN,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { createContext, use, useState } from 'react';
|
|
2
|
-
import GlobalState from "./GlobalState.js";
|
|
3
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
4
|
-
const Context = /*#__PURE__*/createContext(null);
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Gets {@link GlobalState} instance from the context. In most cases
|
|
8
|
-
* you should use {@link useGlobalState}, and other hooks to interact with
|
|
9
|
-
* the global state, instead of accessing it directly.
|
|
10
|
-
* @return
|
|
11
|
-
*/
|
|
12
|
-
export function getGlobalState() {
|
|
13
|
-
// TODO: Think about it: on one hand we on purpose called this function
|
|
14
|
-
// as getGlobalState(), so that ppl looking for the state hook prefer using
|
|
15
|
-
// useGlobalState(), while this getGlobalState() is reserved for nieche cases;
|
|
16
|
-
// on the other hand, perhaps we can rename it into useSomething, to both
|
|
17
|
-
// follow conventions, and to keep stuff clearly named at the same time.
|
|
18
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
19
|
-
const globalState = use(Context);
|
|
20
|
-
if (!globalState) throw new Error('Missing GlobalStateProvider');
|
|
21
|
-
return globalState;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* @category Hooks
|
|
26
|
-
* @desc Gets SSR context.
|
|
27
|
-
* @param throwWithoutSsrContext If `true` (default),
|
|
28
|
-
* this hook will throw if no SSR context is attached to the global state;
|
|
29
|
-
* set `false` to not throw in such case. In either case the hook will throw
|
|
30
|
-
* if the {@link <GlobalStateProvider>} (hence the state) is missing.
|
|
31
|
-
* @returns SSR context.
|
|
32
|
-
* @throws
|
|
33
|
-
* - If current component has no parent {@link <GlobalStateProvider>}
|
|
34
|
-
* in the rendered React tree.
|
|
35
|
-
* - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
|
|
36
|
-
* to the global state provided by {@link <GlobalStateProvider>}.
|
|
37
|
-
*/
|
|
38
|
-
export function getSsrContext(throwWithoutSsrContext = true) {
|
|
39
|
-
const {
|
|
40
|
-
ssrContext
|
|
41
|
-
} = getGlobalState();
|
|
42
|
-
if (!ssrContext && throwWithoutSsrContext) {
|
|
43
|
-
throw new Error('No SSR context found');
|
|
44
|
-
}
|
|
45
|
-
return ssrContext;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Provides global state to its children.
|
|
49
|
-
* @param prop.children Component children, which will be provided with
|
|
50
|
-
* the global state, and rendered in place of the provider.
|
|
51
|
-
* @param prop.initialState Initial content of the global state.
|
|
52
|
-
* @param prop.ssrContext Server-side rendering (SSR) context.
|
|
53
|
-
* @param prop.stateProxy This option is useful for code
|
|
54
|
-
* splitting and SSR implementation:
|
|
55
|
-
* - If `true`, this provider instance will fetch and reuse the global state
|
|
56
|
-
* from a parent provider.
|
|
57
|
-
* - If `GlobalState` instance, it will be used by this provider.
|
|
58
|
-
* - If not given, a new `GlobalState` instance will be created and used.
|
|
59
|
-
*/
|
|
60
|
-
const GlobalStateProvider = ({
|
|
61
|
-
children,
|
|
62
|
-
...rest
|
|
63
|
-
}) => {
|
|
64
|
-
const [localState, setLocalState] = useState();
|
|
65
|
-
let state;
|
|
66
|
-
|
|
67
|
-
// Below we cast `rest.stateProxy` as "boolean" for safe backward
|
|
68
|
-
// compatibility with plain JavaScript (as TypeScript typings only
|
|
69
|
-
// permit "true" or GlobalState value; while legacy codebase may
|
|
70
|
-
// pass in a boolean value here, occasionally equal "false").
|
|
71
|
-
if ('stateProxy' in rest && rest.stateProxy) {
|
|
72
|
-
if (localState) setLocalState(undefined);
|
|
73
|
-
state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
|
|
74
|
-
} else if (localState) {
|
|
75
|
-
state = localState;
|
|
76
|
-
} else {
|
|
77
|
-
const {
|
|
78
|
-
initialState,
|
|
79
|
-
ssrContext
|
|
80
|
-
} = rest;
|
|
81
|
-
state = new GlobalState(typeof initialState === 'function' ? initialState() : initialState, ssrContext);
|
|
82
|
-
setLocalState(state);
|
|
83
|
-
}
|
|
84
|
-
return /*#__PURE__*/_jsx(Context, {
|
|
85
|
-
value: state,
|
|
86
|
-
children: children
|
|
87
|
-
});
|
|
88
|
-
};
|
|
89
|
-
export default GlobalStateProvider;
|
|
90
|
-
//# sourceMappingURL=GlobalStateProvider.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"GlobalStateProvider.js","names":["createContext","use","useState","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localState","setLocalState","state","stateProxy","undefined","initialState","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nimport type { ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link <GlobalStateProvider>} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link <GlobalStateProvider>}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link <GlobalStateProvider>}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = (NewStateProps<StateT, SsrContextT> | {\n stateProxy: GlobalState<StateT, SsrContextT> | true;\n}) & {\n children?: ReactNode;\n};\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAEEA,aAAa,EACbC,GAAG,EACHC,QAAQ,QACH,OAAO;AAAC,OAERC,WAAW;AAAA,SAAAC,GAAA,IAAAC,IAAA;AAKlB,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGL,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACK,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGA,CAI1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KACtD;EAGd,MAAM,CAACC,UAAU,EAAEC,aAAa,CAAC,GAAGf,QAAQ,CAAM,CAAC;EAEnD,IAAIgB,KAAU;;EAEd;EACA;EACA;EACA;EACA,IAAI,YAAY,IAAIH,IAAI,IAAKA,IAAI,CAACI,UAAsB,EAAE;IACxD,IAAIH,UAAU,EAAEC,aAAa,CAACG,SAAS,CAAC;IACxCF,KAAK,GAAGH,IAAI,CAACI,UAAU,KAAK,IAAI,GAAGZ,cAAc,CAAC,CAAC,GAAGQ,IAAI,CAACI,UAAU;EACvE,CAAC,MAAM,IAAIH,UAAU,EAAE;IACrBE,KAAK,GAAGF,UAAU;EACpB,CAAC,MAAM;IACL,MAAM;MACJK,YAAY;MACZT;IACF,CAAC,GAAGG,IAA0C;IAE9CG,KAAK,GAAG,IAAIf,WAAW,CACrB,OAAOkB,YAAY,KAAK,UAAU,GAAIA,YAAY,CAAkB,CAAC,GAAGA,YAAY,EACpFT,UACF,CAAC;IAEDK,aAAa,CAACC,KAAK,CAAC;EACtB;EAEA,oBAAOb,IAAA,CAACC,OAAO;IAACgB,KAAK,EAAEJ,KAAM;IAAAJ,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeD,mBAAmB","ignoreList":[]}
|
package/build/code/SsrContext.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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: Array<Promise<void>> = [];\n\n constructor(public state?: StateT) { }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAKtCC,WAAWA,CAAQC,KAAc,EAAE;IAAAC,eAAA,gBAJlB,KAAK;IAAAA,eAAA,kBAEU,EAAE;IAAA,KAEfD,KAAc,GAAdA,KAAc;EAAI;AACvC","ignoreList":[]}
|
package/build/code/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","loadAsyncData","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type LoadAsyncDataI,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateI,\n getGlobalState,\n getSsrContext,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n SsrContext: typeof SsrContext<StateT>;\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n loadAsyncData: LoadAsyncDataI<StateT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"OAAOA,WAAW;AAAA,OAEXC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAAA,OAGRC,UAAU;AAAA,OAEVC,kBAAkB;AAAA,SAavBC,aAAa,EACbC,oBAAoB,EACpBC,YAAY;AAAA,OAGPC,cAAc;AAYrB,SAIET,WAAW,EACXC,mBAAmB,EACnBG,UAAU,EAOVF,cAAc,EACdC,aAAa,EACbG,aAAa,EACbC,oBAAoB,EACpBF,kBAAkB,EAClBG,YAAY,EACZC,cAAc;;AAGhB;;AAiBA,MAAMC,GAAG,GAAG;EACV;EACA;EACA;EACAV,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVF,cAAc;EACdC,aAAa;EACbG,aAAa;EACbC,oBAAoB;EACpBF,kBAAkB;EAClBG,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
|