@dr.pogodin/react-global-state 0.15.0 → 0.16.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.
@@ -4,6 +4,8 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
+ exports.DEFAULT_MAXAGE = void 0;
8
+ exports.load = load;
7
9
  exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
8
10
  exports.useAsyncData = useAsyncData;
9
11
  var _react = require("react");
@@ -16,7 +18,7 @@ var _utils = require("./utils");
16
18
  * Loads and uses async data into the GlobalState path.
17
19
  */
18
20
 
19
- const DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
21
+ const DEFAULT_MAXAGE = exports.DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
20
22
 
21
23
  function newAsyncDataEnvelope(initialData = null, {
22
24
  numRefs = 0,
@@ -43,22 +45,37 @@ function newAsyncDataEnvelope(initialData = null, {
43
45
  * @return Resolves once the operation is done.
44
46
  * @ignore
45
47
  */
46
- async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
48
+ async function load(path, loader, globalState, old, operationId = `C${(0, _uuid.v4)()}`) {
47
49
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
50
  /* eslint-disable no-console */
49
- console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
51
+ console.log(`ReactGlobalState: async data (re-)loading. Path: "${path || ''}"`);
50
52
  /* eslint-enable no-console */
51
53
  }
52
- const operationId = opIdPrefix + (0, _uuid.v4)();
53
54
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
54
55
  globalState.set(operationIdPath, operationId);
55
- const dataOrLoader = loader(oldData || globalState.get(path).data);
56
- const data = dataOrLoader instanceof Promise ? await dataOrLoader : dataOrLoader;
56
+ let definedOld = old;
57
+ if (!definedOld) {
58
+ // TODO: Can we improve the typing, to avoid ForceT?
59
+ const e = globalState.get(path);
60
+ definedOld = {
61
+ data: e.data,
62
+ timestamp: e.timestamp
63
+ };
64
+ }
65
+ const dataOrPromise = loader(definedOld.data, {
66
+ isAborted: () => {
67
+ // TODO: Can we improve the typing, to avoid ForceT?
68
+ const opid = globalState.get(path).operationId;
69
+ return opid !== operationId;
70
+ },
71
+ oldDataTimestamp: definedOld.timestamp
72
+ });
73
+ const data = dataOrPromise instanceof Promise ? await dataOrPromise : dataOrPromise;
57
74
  const state = globalState.get(path);
58
75
  if (operationId === state.operationId) {
59
76
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
60
77
  /* eslint-disable no-console */
61
- console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
78
+ console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path || ''}"`);
62
79
  console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
63
80
  /* eslint-enable no-console */
64
81
  }
@@ -78,56 +95,13 @@ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
78
95
 
79
96
  /**
80
97
  * Resolves asynchronous data, and stores them at given `path` of global
81
- * state. When multiple components rely on asynchronous data at the same `path`,
82
- * the data are resolved once, and reused until their age is within specified
83
- * bounds. Once the data are stale, the hook allows to refresh them. It also
84
- * garbage-collects stale data from the global state when the last component
85
- * relying on them is unmounted.
86
- * @param path Dot-delimitered state path, where data envelop is
87
- * stored.
88
- * @param loader Asynchronous function which resolves (loads)
89
- * data, which should be stored at the global state `path`. When multiple
90
- * components
91
- * use `useAsyncData()` hook for the same `path`, the library assumes that all
92
- * hook instances are called with the same `loader` (_i.e._ whichever of these
93
- * loaders is used to resolve async data, the result is acceptable to be reused
94
- * in all related components).
95
- * @param options Additional options.
96
- * @param options.deps An array of dependencies, which trigger
97
- * data reload when changed. Given dependency changes are watched shallowly
98
- * (similarly to the standard React's
99
- * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
100
- * @param options.noSSR If `true`, this hook won't load data during
101
- * server-side rendering.
102
- * @param options.garbageCollectAge The maximum age of data
103
- * (in milliseconds), after which they are dropped from the state when the last
104
- * component referencing them via `useAsyncData()` hook unmounts. Defaults to
105
- * `maxage` option value.
106
- * @param options.maxage The maximum age of
107
- * data (in milliseconds) acceptable to the hook's caller. If loaded data are
108
- * older than this value, `null` is returned instead. Defaults to 5 minutes.
109
- * @param options.refreshAge The maximum age of data
110
- * (in milliseconds), after which their refreshment will be triggered when
111
- * any component referencing them via `useAsyncData()` hook (re-)renders.
112
- * Defaults to `maxage` value.
113
- * @return Returns an object with three fields: `data` holds the actual result of
114
- * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
115
- * is a boolean flag, which is `true` if data are being loaded (the hook is
116
- * waiting for `loader` function resolution); `timestamp` (in milliseconds)
117
- * is Unix timestamp of related data currently loaded into the global state.
118
- *
119
- * Note that loaded data, if any, are stored at the given `path` of global state
120
- * along with related meta-information, using slightly different state segment
121
- * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
122
- * can be accessed, and even modified using other hooks,
123
- * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
124
- * `useAsyncData()` hooks logic.
98
+ * state.
125
99
  */
126
100
 
127
101
  function useAsyncData(path, loader, options = {}) {
128
- const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
129
- const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
130
- const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
102
+ const maxage = options.maxage ?? DEFAULT_MAXAGE;
103
+ const refreshAge = options.refreshAge ?? maxage;
104
+ const garbageCollectAge = options.garbageCollectAge ?? maxage;
131
105
 
132
106
  // Note: here we can't depend on useGlobalState() to init the initial value,
133
107
  // because that way we'll have issues with SSR (see details below).
@@ -145,12 +119,15 @@ function useAsyncData(path, loader, options = {}) {
145
119
  heap.reload = customLoader => {
146
120
  const localLoader = customLoader || heap.loader;
147
121
  if (!localLoader || !heap.globalState) throw Error('Internal error');
148
- return load(heap.path, localLoader, heap.globalState, null);
122
+ return load(heap.path, localLoader, heap.globalState);
149
123
  };
150
124
  }
151
125
  if (globalState.ssrContext && !options.noSSR) {
152
126
  if (!state.timestamp && !state.operationId) {
153
- globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
127
+ globalState.ssrContext.pending.push(load(path, loader, globalState, {
128
+ data: state.data,
129
+ timestamp: state.timestamp
130
+ }, `S${(0, _uuid.v4)()}`));
154
131
  }
155
132
  } else {
156
133
  // This takes care about the client-side reference counting, and garbage
@@ -194,9 +171,22 @@ function useAsyncData(path, loader, options = {}) {
194
171
  (0, _react.useEffect)(() => {
195
172
  // eslint-disable-line react-hooks/rules-of-hooks
196
173
  const state2 = globalState.get(path);
197
- if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
198
- load(path, loader, globalState, state2.data);
174
+ const {
175
+ deps
176
+ } = options;
177
+ if (
178
+ // The hook is called with a list of dependencies, that mismatch
179
+ // dependencies last used to retrieve the data at given path.
180
+ deps && globalState.hasChangedDependencies(path || '', deps)
181
+
182
+ // Data at the path are stale, and are not being loaded.
183
+ || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
199
184
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
185
+ if (!deps) globalState.dropDependencies(path || '');
186
+ load(path, loader, globalState, {
187
+ data: state2.data,
188
+ timestamp: state2.timestamp
189
+ });
200
190
  }
201
191
  });
202
192
  (0, _react.useEffect)(() => {
@@ -205,7 +195,7 @@ function useAsyncData(path, loader, options = {}) {
205
195
  deps
206
196
  } = options;
207
197
  if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
208
- load(path, loader, globalState, null);
198
+ load(path, loader, globalState);
209
199
  }
210
200
 
211
201
  // Here we need to default to empty array, so that this hook is re-evaluated
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","dataOrLoader","get","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport 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 AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\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 { 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 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 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\n const dataOrLoader = loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n\n const data: DataT = dataOrLoader instanceof Promise\n ? await dataOrLoader : dataOrLoader;\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:', cloneDeepForLog(data, path ?? ''));\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n 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 === 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 const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState, null);\n };\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.dropDependencies(path || '');\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 useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\n }\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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":";;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBA,MAAMO,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hD,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE0C,MAAM,CAAC/C,IAAI,CAAC;QAC5CiD,aAAa,GAAG,IAAI,CAAC,CAAC;MACxB;IACF,CAAC,CAAC;IAEF,IAAAJ,gBAAS,EAAC,MAAM;MAAE;MAChB,MAAM;QAAEM;MAAK,CAAC,GAAGxB,OAAO;MACxB,IAAIwB,IAAI,IAAI9C,WAAW,CAAC+C,sBAAsB,CAACjD,IAAI,IAAI,EAAE,EAAEgD,IAAI,CAAC,IAAI,CAACF,aAAa,EAAE;QAClF/C,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAE,IAAI,CAAC;MACvC;;MAEF;MACA;MACA;IACA,CAAC,EAAEsB,OAAO,CAACwB,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;EAC1B;EAEA,MAAM,CAACE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCnD,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE4B,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG6B,UAAU,CAACtD,SAAS,GAAG,IAAI,GAAGsD,UAAU,CAACrD,IAAI;IACzEuD,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACpD,WAAW,CAAC;IACxCoC,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBtC,SAAS,EAAEsD,UAAU,CAACtD;EACxB,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","load","path","loader","globalState","old","uuid","process","env","NODE_ENV","isDebugMode","console","log","operationIdPath","set","definedOld","e","get","dataOrPromise","isAborted","opid","oldDataTimestamp","Promise","state","groupCollapsed","cloneDeepForLog","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","Error","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","dropDependencies","loadTriggered","deps","hasChangedDependencies","charAt","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n 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 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 */\nexport async function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null, timestamp: number },\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n });\n\n const data: DataT | null = dataOrPromise instanceof Promise\n ? await dataOrPromise : dataOrPromise;\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: async data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\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.\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = (customLoader?: AsyncDataLoaderT<DataT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n }\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`),\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.dropDependencies(path || '');\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 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.charAt(0) === 'S')\n )\n ) {\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n if (!deps) globalState.dropDependencies(path || '');\n load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (\n deps\n && globalState.hasChangedDependencies(path || '', deps)\n && !loadTriggered\n ) {\n load(path, loader, globalState);\n }\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.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 reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { 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"],"m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EAEA,MAAM,CAACG,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCtD,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAEgC,MAAM,GAAGL,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG4B,UAAU,CAACzD,SAAS,GAAG,IAAI,GAAGyD,UAAU,CAACxD,IAAI;IACzE0D,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACvD,WAAW,CAAC;IACxCuC,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBzC,SAAS,EAAEyD,UAAU,CAACzD;EACxB,CAAC;AACH","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<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\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\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, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAqCA;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;;AASA,SAASK,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAA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,CAACY,GAAG,CAACR,EAAE,CAAEN,IAAI,CAAC;QAC3C,IAAIyB,KAAK,KAAKnB,EAAE,CAAEmB,KAAK,EAAEnB,EAAE,CAAEE,OAAO,CAACkB,IAAI,CAAC,CAAC;MAC7C;IACF,CAAC;EACH;EACApB,EAAE,GAAGF,GAAG,CAACG,OAAQ;EAEjBD,EAAE,CAACJ,WAAW,GAAGA,WAAW;EAC5BI,EAAE,CAACN,IAAI,GAAGA,IAAI;EAEdM,EAAE,CAACmB,KAAK,GAAG,IAAAM,2BAAoB,EAC7BzB,EAAE,CAACqB,SAAS,EACZ,MAAMrB,EAAE,CAAEJ,WAAW,CAACY,GAAG,CAAkBR,EAAE,CAAEN,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMK,EAAE,CAAEJ,WAAW,CAACY,GAAG,CACvBR,EAAE,CAAEN,IAAI,EACR;IAAEC,YAAY;IAAE+B,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAED,IAAAC,gBAAS,EAAC,MAAM;IACd,MAAM;MAAEH;IAAQ,CAAC,GAAG1B,GAAG,CAACG,OAAQ;IAChCL,WAAW,CAACgC,KAAK,CAACJ,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM5B,WAAW,CAACiC,OAAO,CAACL,OAAO,CAAC;EAC3C,CAAC,EAAE,CAAC5B,WAAW,CAAC,CAAC;EAEjB,IAAA+B,gBAAS,EAAC,MAAM;IACd7B,GAAG,CAACG,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC9B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACM,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcvC,cAAc","ignoreList":[]}
1
+ {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","state","emit","subscribe","addListener","bind","watcher","useSyncExternalStore","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\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 cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<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 initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n\n let rc: GlobalStateRef;\n if (!ref.current) {\n const emitter = new Emitter();\n ref.current = {\n emitter,\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value)\n ? value(rc!.globalState.get(rc!.path))\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc!.path || ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc!.globalState.set<ForceT, unknown>(rc!.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc!.state) rc!.emitter.emit();\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n subscribe: emitter.addListener.bind(emitter),\n watcher: () => {\n const state = rc!.globalState.get(rc!.path);\n if (state !== rc!.state) rc!.emitter.emit();\n },\n };\n }\n rc = ref.current!;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n rc.subscribe,\n () => rc!.globalState.get<ForceT, unknown>(rc!.path, { initialValue }),\n\n () => rc!.globalState.get<ForceT, unknown>(\n rc!.path,\n { initialValue, initialState: true },\n ),\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<Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAVA;;AAqCA;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;;AAiBA,SAASK,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAiB,CAAC;EAEpC,IAAIC,EAAkB;EACtB,IAAI,CAACF,GAAG,CAACG,OAAO,EAAE;IAChB,MAAMC,OAAO,GAAG,IAAIC,gBAAO,CAAC,CAAC;IAC7BL,GAAG,CAACG,OAAO,GAAG;MACZC,OAAO;MACPN,WAAW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E,GAAGF,GAAG,CAACG,OAAQ;EAEjBD,EAAE,CAACJ,WAAW,GAAGA,WAAW;EAC5BI,EAAE,CAACN,IAAI,GAAGA,IAAI;EAEdM,EAAE,CAACmB,KAAK,GAAG,IAAAM,2BAAoB,EAC7BzB,EAAE,CAACqB,SAAS,EACZ,MAAMrB,EAAE,CAAEJ,WAAW,CAACY,GAAG,CAAkBR,EAAE,CAAEN,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EAEtE,MAAMK,EAAE,CAAEJ,WAAW,CAACY,GAAG,CACvBR,EAAE,CAAEN,IAAI,EACR;IAAEC,YAAY;IAAE+B,YAAY,EAAE;EAAK,CACrC,CACF,CAAC;EAED,IAAAC,gBAAS,EAAC,MAAM;IACd,MAAM;MAAEH;IAAQ,CAAC,GAAG1B,GAAG,CAACG,OAAQ;IAChCL,WAAW,CAACgC,KAAK,CAACJ,OAAO,CAAC;IAC1BA,OAAO,CAAC,CAAC;IACT,OAAO,MAAM5B,WAAW,CAACiC,OAAO,CAACL,OAAO,CAAC;EAC3C,CAAC,EAAE,CAAC5B,WAAW,CAAC,CAAC;EAEjB,IAAA+B,gBAAS,EAAC,MAAM;IACd7B,GAAG,CAACG,OAAO,CAAEuB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAAC9B,IAAI,CAAC,CAAC;EAEV,OAAO,CAACM,EAAE,CAACmB,KAAK,EAAEnB,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAA0B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcvC,cAAc","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalState.js","names":["get","isFunction","isObject","isNil","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type 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 #dependencies: { [key: string]: Readonly<any[]> } = {};\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 * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[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 hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps[i] !== deps[i];\n }\n this.#dependencies[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 = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', 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 (let i = 0; i < watchers.length; ++i) {\n watchers[i]();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | 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 (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | 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 (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SACEA,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAOEC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,aAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,SAAA,oBAAAF,OAAA;AAAA,IAAAG,eAAA,oBAAAH,OAAA;AAAA,IAAAI,aAAA,oBAAAJ,OAAA;AAO1E,eAAe,MAAMK,WAAW,CAG9B;EAiBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAtBFC,0BAAA,OAAAV,aAAa,EAAuC,CAAC,CAAC;IAEtDU,0BAAA,OAAAR,aAAa;IAEb;IACA;IACA;IACA;IACAQ,0BAAA,OAAAP,SAAS,EAAgB,EAAE;IAE3BO,0BAAA,OAAAN,eAAe;IAEfM,0BAAA,OAAAL,aAAa;IAWXM,qBAAA,CAAKN,aAAa,EAAlB,IAAI,EAAiBG,YAAJ,CAAC;IAClBG,qBAAA,CAAKT,aAAa,EAAlB,IAAI,EAAiBM,YAAJ,CAAC;IAElB,IAAIC,UAAU,EAAE;MACd;MACAA,UAAU,CAACG,KAAK,GAAG,KAAK;MACxBH,UAAU,CAACI,OAAO,GAAG,EAAE;MACvBJ,UAAU,CAACK,KAAK,GAAGC,qBAAA,CAAKV,aAAa,EAAlB,IAAiB,CAAC;MACrC;;MA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AG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC/C,UAAU,EAAE,MAAM,IAAIgD,KAAK,CAAC1D,gBAAgB,CAAC;IAEtD,MAAM6C,QAAQ,GAAG7B,qBAAA,CAAKZ,SAAS,EAAd,IAAa,CAAC;IAC/B,IAAIyC,QAAQ,CAACc,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCZ,QAAQ,CAACiB,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"GlobalState.js","names":["get","isFunction","isObject","isNil","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type 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 #dependencies: { [key: string]: Readonly<any[]> } = {};\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 * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[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 hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[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 = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', 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 (let i = 0; i < watchers.length; ++i) {\n watchers[i]!();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | 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 (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | 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 (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SACEA,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAOEC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,aAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,SAAA,oBAAAF,OAAA;AAAA,IAAAG,eAAA,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CAACC,YAAY,CAACF,MAAM,CAAC,CAAE,GAAGN,KAAK;MACpC;MAEA9B,qBAAA,CAAKN,aAAa,EAAlB,IAAI,EAAiByC,IAAI,CAAChC,KAAT,CAAC;MAElB,IAAI,CAAC0B,iBAAiB,CAACf,IAAI,EAAEgB,KAAK,CAAC;IACrC;IACA,OAAOA,KAAK;EACd;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;EACEc,OAAOA,CAACC,QAAmB,EAAE;IAC3B,IAAI,IAAI,CAAC/C,UAAU,EAAE,MAAM,IAAIgD,KAAK,CAAC1D,gBAAgB,CAAC;IAEtD,MAAM6C,QAAQ,GAAG7B,qBAAA,CAAKZ,SAAS,EAAd,IAAa,CAAC;IAC/B,MAAM6C,GAAG,GAAGJ,QAAQ,CAACc,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIR,GAAG,IAAI,CAAC,EAAE;MACZJ,QAAQ,CAACI,GAAG,CAAC,GAAGJ,QAAQ,CAACA,QAAQ,CAACd,MAAM,GAAG,CAAC,CAAE;MAC9Cc,QAAQ,CAACe,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC/C,UAAU,EAAE,MAAM,IAAIgD,KAAK,CAAC1D,gBAAgB,CAAC;IAEtD,MAAM6C,QAAQ,GAAG7B,qBAAA,CAAKZ,SAAS,EAAd,IAAa,CAAC;IAC/B,IAAIyC,QAAQ,CAACc,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCZ,QAAQ,CAACiB,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
@@ -60,7 +60,7 @@ export function getSsrContext() {
60
60
  * - If `GlobalState` instance, it will be used by this provider.
61
61
  * - If not given, a new `GlobalState` instance will be created and used.
62
62
  */
63
- export default function GlobalStateProvider(_ref) {
63
+ const GlobalStateProvider = _ref => {
64
64
  let {
65
65
  children,
66
66
  ...rest
@@ -85,5 +85,6 @@ export default function GlobalStateProvider(_ref) {
85
85
  value: state.current,
86
86
  children: children
87
87
  });
88
- }
88
+ };
89
+ export default GlobalStateProvider;
89
90
  //# sourceMappingURL=GlobalStateProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\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 &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,UAAU,CAACK,OAAO,CAAC;EACvC;EACA,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,CAAA,EAIF;EAAA,IADzBC,sBAAsB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAE7B,MAAM;IAAEG;EAAW,CAAC,GAAGR,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACQ,UAAU,IAAIJ,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOM,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,mBAAmBA,CAAAC,IAAA,EAKzC;EAAA,IADA;IAAEC,QAAQ;IAAE,GAAGC;EAAoD,CAAC,GAAAF,IAAA;EAEpE,MAAMG,KAAK,GAAGlB,MAAM,CAAmC,CAAC;EACxD,IAAI,CAACkB,KAAK,CAACC,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIF,IAAI,IAAIA,IAAI,CAACG,UAAU,EAAE;MAC3C,IAAIH,IAAI,CAACG,UAAU,KAAK,IAAI,EAAEF,KAAK,CAACC,OAAO,GAAGd,cAAc,CAAC,CAAC,CAAC,KAC1Da,KAAK,CAACC,OAAO,GAAGF,IAAI,CAACG,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGI,IAA0C;MAE/EC,KAAK,CAACC,OAAO,GAAG,IAAIlB,WAAW,CAC7BJ,UAAU,CAACwB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\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 &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,UAAU,CAACK,OAAO,CAAC;EACvC;EACA,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,CAAA,EAIF;EAAA,IADzBC,sBAAsB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAE7B,MAAM;IAAEG;EAAW,CAAC,GAAGR,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACQ,UAAU,IAAIJ,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOM,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGC,IAAA,IAG+C;EAAA,IAAzE;IAAEC,QAAQ;IAAE,GAAGC;EAAoD,CAAC,GAAAF,IAAA;EACpE,MAAMG,KAAK,GAAGlB,MAAM,CAAmC,CAAC;EACxD,IAAI,CAACkB,KAAK,CAACC,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIF,IAAI,IAAIA,IAAI,CAACG,UAAU,EAAE;MAC3C,IAAIH,IAAI,CAACG,UAAU,KAAK,IAAI,EAAEF,KAAK,CAACC,OAAO,GAAGd,cAAc,CAAC,CAAC,CAAC,KAC1Da,KAAK,CAACC,OAAO,GAAGF,IAAI,CAACG,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGI,IAA0C;MAE/EC,KAAK,CAACC,OAAO,GAAG,IAAIlB,WAAW,CAC7BJ,UAAU,CAACwB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB,CAAC;AAED,eAAeF,mBAAmB","ignoreList":[]}
@@ -4,8 +4,7 @@ import SsrContext from "./SsrContext";
4
4
  import useAsyncCollection from "./useAsyncCollection";
5
5
  import { newAsyncDataEnvelope, useAsyncData } from "./useAsyncData";
6
6
  import useGlobalState from "./useGlobalState";
7
- export * from "./useAsyncData";
8
- export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, SsrContext, useAsyncCollection, useGlobalState };
7
+ export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState };
9
8
  const api = {
10
9
  getGlobalState,
11
10
  getSsrContext,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n} from './useAsyncCollection';\n\nimport {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport * from './useAsyncData';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n useAsyncCollection,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAIzB,SAEEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAIrB;AAMA,SACEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBG,UAAU,EACVC,kBAAkB,EAClBG,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBK,oBAAoB;EACpBF,UAAU;EACVC,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAKzB,SAMEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAQrB,SAMEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBK,oBAAoB;EACpBF,UAAU;EACVC,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}