@dr.pogodin/react-global-state 0.10.0-alpha.2 → 0.10.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +2 -0
  2. package/build/common/GlobalState.js +219 -0
  3. package/build/common/GlobalState.js.map +1 -0
  4. package/build/common/GlobalStateProvider.js +101 -0
  5. package/build/common/GlobalStateProvider.js.map +1 -0
  6. package/build/common/SsrContext.js +15 -0
  7. package/build/common/SsrContext.js.map +1 -0
  8. package/build/common/index.js +81 -0
  9. package/build/common/index.js.map +1 -0
  10. package/build/common/useAsyncCollection.js +61 -0
  11. package/build/common/useAsyncCollection.js.map +1 -0
  12. package/build/common/useAsyncData.js +204 -0
  13. package/build/common/useAsyncData.js.map +1 -0
  14. package/build/common/useGlobalState.js +114 -0
  15. package/build/common/useGlobalState.js.map +1 -0
  16. package/build/common/utils.js +43 -0
  17. package/build/common/utils.js.map +1 -0
  18. package/build/module/GlobalState.js +230 -0
  19. package/build/module/GlobalState.js.map +1 -0
  20. package/build/module/GlobalStateProvider.js +94 -0
  21. package/build/module/GlobalStateProvider.js.map +1 -0
  22. package/build/module/SsrContext.js +9 -0
  23. package/build/module/SsrContext.js.map +1 -0
  24. package/build/module/index.js +19 -0
  25. package/build/module/index.js.map +1 -0
  26. package/build/module/useAsyncCollection.js +56 -0
  27. package/build/module/useAsyncCollection.js.map +1 -0
  28. package/build/module/useAsyncData.js +199 -0
  29. package/build/module/useAsyncData.js.map +1 -0
  30. package/build/module/useGlobalState.js +109 -0
  31. package/build/module/useGlobalState.js.map +1 -0
  32. package/build/module/utils.js +35 -0
  33. package/build/module/utils.js.map +1 -0
  34. package/build/{GlobalState.d.ts → types/GlobalState.d.ts} +6 -6
  35. package/build/{GlobalStateProvider.d.ts → types/GlobalStateProvider.d.ts} +8 -8
  36. package/build/types/index.d.ts +24 -0
  37. package/build/{useAsyncCollection.d.ts → types/useAsyncCollection.d.ts} +6 -2
  38. package/build/{useAsyncData.d.ts → types/useAsyncData.d.ts} +6 -3
  39. package/build/{useGlobalState.d.ts → types/useGlobalState.d.ts} +7 -2
  40. package/build/{utils.d.ts → types/utils.d.ts} +6 -1
  41. package/package.json +43 -38
  42. package/src/GlobalState.ts +15 -10
  43. package/src/GlobalStateProvider.tsx +26 -15
  44. package/src/index.ts +57 -19
  45. package/src/useAsyncCollection.ts +21 -5
  46. package/src/useAsyncData.ts +43 -20
  47. package/src/useGlobalState.ts +30 -11
  48. package/src/utils.ts +11 -3
  49. package/tsconfig.json +10 -4
  50. package/tsconfig.types.json +14 -0
  51. package/build/GlobalState.js +0 -193
  52. package/build/GlobalStateProvider.js +0 -103
  53. package/build/SsrContext.js +0 -10
  54. package/build/index.d.ts +0 -8
  55. package/build/index.js +0 -23
  56. package/build/useAsyncCollection.js +0 -14
  57. package/build/useAsyncData.js +0 -150
  58. package/build/useGlobalState.js +0 -49
  59. package/build/utils.js +0 -25
  60. package/build/withGlobalStateType.d.ts +0 -39
  61. package/build/withGlobalStateType.js +0 -55
  62. package/src/withGlobalStateType.ts +0 -118
  63. /package/build/{SsrContext.d.ts → types/SsrContext.d.ts} +0 -0
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
9
+ var _lodash = require("lodash");
10
+ var _react = require("react");
11
+ var _uuid = require("uuid");
12
+ var _jsUtils = require("@dr.pogodin/js-utils");
13
+ var _GlobalStateProvider = require("./GlobalStateProvider");
14
+ var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
15
+ var _utils = require("./utils");
16
+ /**
17
+ * Loads and uses async data into the GlobalState path.
18
+ */
19
+
20
+ const DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
21
+
22
+ function newAsyncDataEnvelope(initialData = null) {
23
+ return {
24
+ data: initialData,
25
+ numRefs: 0,
26
+ operationId: '',
27
+ timestamp: 0
28
+ };
29
+ }
30
+ /**
31
+ * Executes the data loading operation.
32
+ * @param path Data segment path inside the global state.
33
+ * @param loader Data loader.
34
+ * @param globalState The global state instance.
35
+ * @param oldData Optional. Previously fetched data, currently stored in
36
+ * the state, if already fetched by the caller; otherwise, they will be fetched
37
+ * by the load() function itself.
38
+ * @param opIdPrefix operationId prefix to use, which should be
39
+ * 'C' at the client-side (default), or 'S' at the server-side (within SSR
40
+ * context).
41
+ * @return Resolves once the operation is done.
42
+ * @ignore
43
+ */
44
+ async function load(path, loader, globalState, oldData, opIdPrefix = 'C') {
45
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
46
+ /* eslint-disable no-console */
47
+ console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
48
+ /* eslint-enable no-console */
49
+ }
50
+
51
+ const operationId = opIdPrefix + (0, _uuid.v4)();
52
+ const operationIdPath = path ? `${path}.operationId` : 'operationId';
53
+ globalState.set(operationIdPath, operationId);
54
+ const data = await loader(oldData || globalState.get(path).data);
55
+ const state = globalState.get(path);
56
+ if (operationId === state.operationId) {
57
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
58
+ /* eslint-disable no-console */
59
+ console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
60
+ console.log('Data:', (0, _lodash.cloneDeep)(data));
61
+ /* eslint-enable no-console */
62
+ }
63
+
64
+ globalState.set(path, {
65
+ ...state,
66
+ data,
67
+ operationId: '',
68
+ timestamp: Date.now()
69
+ });
70
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
71
+ /* eslint-disable no-console */
72
+ console.groupEnd();
73
+ /* eslint-enable no-console */
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Resolves asynchronous data, and stores them at given `path` of global
80
+ * state. When multiple components rely on asynchronous data at the same `path`,
81
+ * the data are resolved once, and reused until their age is within specified
82
+ * bounds. Once the data are stale, the hook allows to refresh them. It also
83
+ * garbage-collects stale data from the global state when the last component
84
+ * relying on them is unmounted.
85
+ * @param path Dot-delimitered state path, where data envelop is
86
+ * stored.
87
+ * @param loader Asynchronous function which resolves (loads)
88
+ * data, which should be stored at the global state `path`. When multiple
89
+ * components
90
+ * use `useAsyncData()` hook for the same `path`, the library assumes that all
91
+ * hook instances are called with the same `loader` (_i.e._ whichever of these
92
+ * loaders is used to resolve async data, the result is acceptable to be reused
93
+ * in all related components).
94
+ * @param options Additional options.
95
+ * @param options.deps An array of dependencies, which trigger
96
+ * data reload when changed. Given dependency changes are watched shallowly
97
+ * (similarly to the standard React's
98
+ * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).
99
+ * @param options.noSSR If `true`, this hook won't load data during
100
+ * server-side rendering.
101
+ * @param options.garbageCollectAge The maximum age of data
102
+ * (in milliseconds), after which they are dropped from the state when the last
103
+ * component referencing them via `useAsyncData()` hook unmounts. Defaults to
104
+ * `maxage` option value.
105
+ * @param options.maxage The maximum age of
106
+ * data (in milliseconds) acceptable to the hook's caller. If loaded data are
107
+ * older than this value, `null` is returned instead. Defaults to 5 minutes.
108
+ * @param options.refreshAge The maximum age of data
109
+ * (in milliseconds), after which their refreshment will be triggered when
110
+ * any component referencing them via `useAsyncData()` hook (re-)renders.
111
+ * Defaults to `maxage` value.
112
+ * @return Returns an object with three fields: `data` holds the actual result of
113
+ * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`
114
+ * is a boolean flag, which is `true` if data are being loaded (the hook is
115
+ * waiting for `loader` function resolution); `timestamp` (in milliseconds)
116
+ * is Unix timestamp of related data currently loaded into the global state.
117
+ *
118
+ * Note that loaded data, if any, are stored at the given `path` of global state
119
+ * along with related meta-information, using slightly different state segment
120
+ * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state
121
+ * can be accessed, and even modified using other hooks,
122
+ * _e.g._ {@link useGlobalState}, but doing so you may interfere with related
123
+ * `useAsyncData()` hooks logic.
124
+ */
125
+
126
+ function useAsyncData(path, loader, options = {}) {
127
+ const maxage = options.maxage === undefined ? DEFAULT_MAXAGE : options.maxage;
128
+ const refreshAge = options.refreshAge === undefined ? maxage : options.refreshAge;
129
+ const garbageCollectAge = options.garbageCollectAge === undefined ? maxage : options.garbageCollectAge;
130
+
131
+ // Note: here we can't depend on useGlobalState() to init the initial value,
132
+ // because that way we'll have issues with SSR (see details below).
133
+ const globalState = (0, _GlobalStateProvider.getGlobalState)();
134
+ const state = globalState.get(path, {
135
+ initialValue: newAsyncDataEnvelope()
136
+ });
137
+ if (globalState.ssrContext && !options.noSSR) {
138
+ if (!state.timestamp && !state.operationId) {
139
+ globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
140
+ }
141
+ } else {
142
+ // This takes care about the client-side reference counting, and garbage
143
+ // collection.
144
+ //
145
+ // Note: the Rules of Hook below are violated by conditional call to a hook,
146
+ // but as the condition is actually server-side or client-side environment,
147
+ // it is effectively non-conditional at the runtime.
148
+ //
149
+ // TODO: Though, maybe there is a way to refactor it into a cleaner code.
150
+ // The same applies to other useEffect() hooks below.
151
+ (0, _react.useEffect)(() => {
152
+ // eslint-disable-line react-hooks/rules-of-hooks
153
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
154
+ const numRefs = globalState.get(numRefsPath);
155
+ globalState.set(numRefsPath, numRefs + 1);
156
+ return () => {
157
+ const state2 = globalState.get(path);
158
+ if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
159
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
160
+ /* eslint-disable no-console */
161
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
162
+ /* eslint-enable no-console */
163
+ }
164
+
165
+ globalState.set(path, {
166
+ ...state2,
167
+ data: null,
168
+ numRefs: 0,
169
+ timestamp: 0
170
+ });
171
+ } else globalState.set(numRefsPath, state2.numRefs - 1);
172
+ };
173
+ }, [garbageCollectAge, globalState, path]);
174
+
175
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
176
+ // special case the otherwise wrong behavior is actually what we need.
177
+
178
+ // Data loading and refreshing.
179
+ let loadTriggered = false;
180
+ (0, _react.useEffect)(() => {
181
+ // eslint-disable-line react-hooks/rules-of-hooks
182
+ const state2 = globalState.get(path);
183
+ if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
184
+ load(path, loader, globalState, state2.data);
185
+ loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
186
+ }
187
+ });
188
+
189
+ const deps = options.deps || [];
190
+ (0, _react.useEffect)(() => {
191
+ // eslint-disable-line react-hooks/rules-of-hooks
192
+ if (!loadTriggered && deps.length) load(path, loader, globalState, null);
193
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
194
+ }
195
+
196
+ const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
197
+ return {
198
+ data: maxage < Date.now() - localState.timestamp ? null : localState.data,
199
+ loading: Boolean(localState.operationId),
200
+ timestamp: localState.timestamp
201
+ };
202
+ }
203
+ var _default = exports.default = useAsyncData;
204
+ //# sourceMappingURL=useAsyncData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncData.js","names":["_lodash","require","_react","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","MIN_MS","newAsyncDataEnvelope","initialData","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","isDebugMode","console","log","uuid","operationIdPath","set","get","state","groupCollapsed","cloneDeep","Date","now","groupEnd","useAsyncData","options","maxage","undefined","refreshAge","garbageCollectAge","getGlobalState","initialValue","ssrContext","noSSR","pending","push","useEffect","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","useGlobalState","loading","Boolean","_default","exports","default"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!loadTriggered && deps.length) load(path, loader, globalState, null);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,IAAAG,QAAA,GAAAH,OAAA;AAEA,IAAAI,oBAAA,GAAAJ,OAAA;AACA,IAAAK,eAAA,GAAAC,sBAAA,CAAAN,O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U,CAAC1C;EACxB,CAAC;AACH;AAAC,IAAA8C,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEczB,YAAY"}
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _lodash = require("lodash");
8
+ var _react = require("react");
9
+ var _jsUtils = require("@dr.pogodin/js-utils");
10
+ var _GlobalStateProvider = require("./GlobalStateProvider");
11
+ var _utils = require("./utils");
12
+ // Hook for updates of global state.
13
+
14
+ /**
15
+ * The primary hook for interacting with the global state, modeled after
16
+ * the standard React's
17
+ * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
18
+ * It subscribes a component to a given `path` of global state, and provides
19
+ * a function to update it. Each time the value at `path` changes, the hook
20
+ * triggers re-render of its host component.
21
+ *
22
+ * **Note:**
23
+ * - For performance, the library does not copy objects written to / read from
24
+ * global state paths. You MUST NOT manually mutate returned state values,
25
+ * or change objects already written into the global state, without explicitly
26
+ * clonning them first yourself.
27
+ * - State update notifications are asynchronous. When your code does multiple
28
+ * global state updates in the same React rendering cycle, all state update
29
+ * notifications are queued and dispatched together, after the current
30
+ * rendering cycle. In other words, in any given rendering cycle the global
31
+ * state values are "fixed", and all changes becomes visible at once in the
32
+ * next triggered rendering pass.
33
+ *
34
+ * @param path Dot-delimitered state path. It can be undefined to
35
+ * subscribe for entire state.
36
+ *
37
+ * Under-the-hood state values are read and written using `lodash`
38
+ * [_.get()](https://lodash.com/docs/4.17.15#get) and
39
+ * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
40
+ * to access state paths which have not been created before.
41
+ * @param initialValue Initial value to set at the `path`, or its
42
+ * factory:
43
+ * - If a function is given, it will act similar to
44
+ * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
45
+ * only if the value at `path` is `undefined`, the function will be executed,
46
+ * and the value it returns will be written to the `path`.
47
+ * - Otherwise, the given value itself will be written to the `path`,
48
+ * if the current value at `path` is `undefined`.
49
+ * @return It returs an array with two elements: `[value, setValue]`:
50
+ *
51
+ * - The `value` is the current value at given `path`.
52
+ *
53
+ * - The `setValue()` is setter function to write a new value to the `path`.
54
+ *
55
+ * Similar to the standard React's `useState()`, it supports
56
+ * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
57
+ * if `setValue()` is called with a function as argument, that function will
58
+ * be called and its return value will be written to `path`. Otherwise,
59
+ * the argument of `setValue()` itself is written to `path`.
60
+ *
61
+ * Also, similar to the standard React's state setters, `setValue()` is
62
+ * stable function: it does not change between component re-renders.
63
+ */ // "Enforced type overload"
64
+ // "Entire state overload"
65
+ // "State evaluation overload"
66
+ function useGlobalState(path, initialValue) {
67
+ const globalState = (0, _GlobalStateProvider.getGlobalState)();
68
+ const ref = (0, _react.useRef)();
69
+ const rc = ref.current || {
70
+ emitter: new _jsUtils.Emitter(),
71
+ globalState,
72
+ path,
73
+ setter: value => {
74
+ const newState = (0, _lodash.isFunction)(value) ? value(rc.state) : value;
75
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
76
+ /* eslint-disable no-console */
77
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
78
+ console.log('New value:', (0, _lodash.cloneDeep)(newState));
79
+ console.groupEnd();
80
+ /* eslint-enable no-console */
81
+ }
82
+
83
+ rc.globalState.set(rc.path, newState);
84
+ },
85
+ state: (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue,
86
+ watcher: () => {
87
+ const state = rc.globalState.get(rc.path);
88
+ if (state !== rc.state) rc.emitter.emit();
89
+ }
90
+ };
91
+ ref.current = rc;
92
+ rc.globalState = globalState;
93
+ rc.path = path;
94
+ rc.state = (0, _react.useSyncExternalStore)(cb => rc.emitter.addListener(cb), () => rc.globalState.get(rc.path, {
95
+ initialValue
96
+ }), () => rc.globalState.get(rc.path, {
97
+ initialValue,
98
+ initialState: true
99
+ }));
100
+ (0, _react.useEffect)(() => {
101
+ const {
102
+ watcher
103
+ } = ref.current;
104
+ globalState.watch(watcher);
105
+ watcher();
106
+ return () => globalState.unWatch(watcher);
107
+ }, [globalState]);
108
+ (0, _react.useEffect)(() => {
109
+ ref.current.watcher();
110
+ }, [path]);
111
+ return [rc.state, rc.setter];
112
+ }
113
+ var _default = exports.default = useGlobalState;
114
+ //# sourceMappingURL=useGlobalState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","rc","current","emitter","Emitter","setter","value","newState","isFunction","state","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeep","groupEnd","set","watcher","get","emit","useSyncExternalStore","cb","addListener","initialState","useEffect","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = React.Dispatch<React.SetStateAction<T>>;\n\ntype GlobalStateRef = {\n emitter: Emitter<[]>;\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n setter: SetterT<unknown>;\n state: unknown;\n watcher: CallbackT;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n initialValue?: ValueOrInitializerT<unknown>,\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<GlobalStateRef>();\n const rc: GlobalStateRef = ref.current || {\n emitter: new Emitter(),\n globalState,\n path,\n setter: (value) => {\n const newState = isFunction(value) ? value(rc.state) : value;\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path || ''\n }`,\n );\n console.log('New value:', cloneDeep(newState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n },\n state: isFunction(initialValue) ? initialValue() : initialValue,\n watcher: () => {\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) rc.emitter.emit();\n },\n };\n ref.current = rc;\n\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => rc.emitter.addListener(cb),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue }),\n () => rc.globalState.get<ForceT, unknown>(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n const { watcher } = ref.current!;\n globalState.watch(watcher);\n watcher();\n return () => globalState.unWatch(watcher);\n }, [globalState]);\n\n useEffect(() => {\n ref.current!.watcher();\n }, [path]);\n\n return [rc.state, rc.setter];\n}\n\nexport default useGlobalState;\n\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, 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;;AAiCA;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,GAjDA,CAmDA;AASA;AAGA;AASA,SAASK,cAAcA,CACrBC,IAAoB,EACpBC,YAA2C,EAClB;EACzB,MAAMC,WAAW,GAAG,IAAAC,mCAAc,EAAC,CAAC;EAEpC,MAAMC,GAAG,GAAG,IAAAC,aAAM,EAAiB,CAAC;EACpC,MAAMC,EAAkB,GAAGF,GAAG,CAACG,OAAO,IAAI;IACxCC,OAAO,EAAE,IAAIC,gBAAO,CAAC,CAAC;IACtBP,WAAW;IACXF,IAAI;IACJU,MAAM,EAAGC,KAAK,IAAK;MACjB,MAAMC,QAAQ,GAAG,IAAAC,kBAAU,EAACF,KAAK,CAAC,GAAGA,KAAK,CAACL,EAAE,CAACQ,KAAK,CAAC,GAAGH,KAAK;MAC5D,IAAII,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;QAC1D;QACAC,OAAO,CAACC,cAAc,CACnB,+DACCd,EAAE,CAACN,IAAI,IAAI,EACZ,EACH,CAAC;QACDmB,OAAO,CAACE,GAAG,CAAC,YAAY,EAAE,IAAAC,iBAAS,EAACV,QAAQ,CAAC,CAAC;QAC9CO,OAAO,CAACI,QAAQ,CAAC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B,GAAG,CAACG,OAAO,CAAEkB,OAAO,CAAC,CAAC;EACxB,CAAC,EAAE,CAACzB,IAAI,CAAC,CAAC;EAEV,OAAO,CAACM,EAAE,CAACQ,KAAK,EAAER,EAAE,CAACI,MAAM,CAAC;AAC9B;AAAC,IAAAyB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEctC,cAAc"}
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isDebugMode = isDebugMode;
7
+ // TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
8
+ // lib.
9
+
10
+ /**
11
+ * Given the type of state, `StateT`, and the type of state path, `PathT`,
12
+ * it evaluates the type of value at that path of the state, if it can be
13
+ * evaluated from the path type (it is possible when `PathT` is a string
14
+ * literal type, and `StateT` elements along this path have appropriate
15
+ * types); otherwise it falls back to the specified `UnknownT` type,
16
+ * which should be set either `never` (for input arguments), or `void`
17
+ * (for return types) - `never` and `void` in those places forbid assignments,
18
+ * and are not auto-inferred to more permissible types.
19
+ *
20
+ * BEWARE: When StateT is any the construct resolves to any for any string
21
+ * paths.
22
+ */
23
+
24
+ /**
25
+ * Returns 'true' if debug logging should be performed; 'false' otherwise.
26
+ *
27
+ * BEWARE: The actual safeguards for the debug logging still should read
28
+ * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
29
+ * // Some debug logging
30
+ * }
31
+ * to ensure that debug code is stripped out by Webpack in production mode.
32
+ *
33
+ * @returns
34
+ * @ignore
35
+ */
36
+ function isDebugMode() {
37
+ try {
38
+ return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
43
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType } from 'lodash';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\ndeclare const force: unique symbol;\ndeclare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch (error) {\n return false;\n }\n}\n"],"mappings":";;;;;;AAIA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF"}
@@ -0,0 +1,230 @@
1
+ import _classPrivateFieldGet from "@babel/runtime/helpers/classPrivateFieldGet";
2
+ import _classPrivateFieldSet from "@babel/runtime/helpers/classPrivateFieldSet";
3
+ function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
4
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
5
+ import { cloneDeep, get, isFunction, isObject, isNil, set, toPath } from 'lodash';
6
+ import { isDebugMode } from "./utils";
7
+ const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
8
+ var _initialState = /*#__PURE__*/new WeakMap();
9
+ var _watchers = /*#__PURE__*/new WeakMap();
10
+ var _nextNotifierId = /*#__PURE__*/new WeakMap();
11
+ var _currentState = /*#__PURE__*/new WeakMap();
12
+ export default class GlobalState {
13
+ /**
14
+ * Creates a new global state object.
15
+ * @param initialState Intial global state content.
16
+ * @param ssrContext Server-side rendering context.
17
+ */
18
+ constructor(initialState, ssrContext) {
19
+ _classPrivateFieldInitSpec(this, _initialState, {
20
+ writable: true,
21
+ value: void 0
22
+ });
23
+ // TODO: It is tempting to replace watchers here by
24
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
25
+ // current watchers for emitting later, and this is not something
26
+ // Emitter supports right now.
27
+ _classPrivateFieldInitSpec(this, _watchers, {
28
+ writable: true,
29
+ value: []
30
+ });
31
+ _classPrivateFieldInitSpec(this, _nextNotifierId, {
32
+ writable: true,
33
+ value: void 0
34
+ });
35
+ _classPrivateFieldInitSpec(this, _currentState, {
36
+ writable: true,
37
+ value: void 0
38
+ });
39
+ _classPrivateFieldSet(this, _currentState, initialState);
40
+ _classPrivateFieldSet(this, _initialState, initialState);
41
+ if (ssrContext) {
42
+ /* eslint-disable no-param-reassign */
43
+ ssrContext.dirty = false;
44
+ ssrContext.pending = [];
45
+ ssrContext.state = _classPrivateFieldGet(this, _currentState);
46
+ /* eslint-enable no-param-reassign */
47
+
48
+ this.ssrContext = ssrContext;
49
+ }
50
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
51
+ /* eslint-disable no-console */
52
+ let msg = 'New ReactGlobalState created';
53
+ if (ssrContext) msg += ' (SSR mode)';
54
+ console.groupCollapsed(msg);
55
+ console.log('Initial state:', cloneDeep(initialState));
56
+ console.groupEnd();
57
+ /* eslint-enable no-console */
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Gets entire state, the same way as .get(null, opts) would do.
63
+ * @param opts.initialState
64
+ * @param opts.initialValue
65
+ */
66
+ getEntireState(opts) {
67
+ let state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
68
+ if (state !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return state;
69
+ const iv = opts.initialValue;
70
+ state = isFunction(iv) ? iv() : iv;
71
+ if (_classPrivateFieldGet(this, _currentState) === undefined) this.setEntireState(state);
72
+ return state;
73
+ }
74
+
75
+ /**
76
+ * Notifies all connected state watchers that a state update has happened.
77
+ */
78
+ notifyStateUpdate(path, value) {
79
+ if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
80
+ /* eslint-disable no-console */
81
+ const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
82
+ console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
83
+ console.log('New value:', cloneDeep(value));
84
+ console.log('New state:', cloneDeep(_classPrivateFieldGet(this, _currentState)));
85
+ console.groupEnd();
86
+ /* eslint-enable no-console */
87
+ }
88
+
89
+ if (this.ssrContext) {
90
+ this.ssrContext.dirty = true;
91
+ this.ssrContext.state = _classPrivateFieldGet(this, _currentState);
92
+ } else if (!_classPrivateFieldGet(this, _nextNotifierId)) {
93
+ _classPrivateFieldSet(this, _nextNotifierId, setTimeout(() => {
94
+ _classPrivateFieldSet(this, _nextNotifierId, undefined);
95
+ const watchers = [..._classPrivateFieldGet(this, _watchers)];
96
+ for (let i = 0; i < watchers.length; ++i) {
97
+ watchers[i]();
98
+ }
99
+ }));
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Sets entire state, the same way as .set(null, value) would do.
105
+ * @param value
106
+ */
107
+ setEntireState(value) {
108
+ if (_classPrivateFieldGet(this, _currentState) !== value) {
109
+ _classPrivateFieldSet(this, _currentState, value);
110
+ this.notifyStateUpdate(null, value);
111
+ }
112
+ return value;
113
+ }
114
+
115
+ /**
116
+ * Gets current or initial value at the specified "path" of the global state.
117
+ * @param path Dot-delimitered state path.
118
+ * @param options Additional options.
119
+ * @param options.initialState If "true" the value will be read
120
+ * from the initial state instead of the current one.
121
+ * @param options.initialValue If the value read from the "path" is
122
+ * "undefined", this "initialValue" will be returned instead. In such case
123
+ * "initialValue" will also be written to the "path" of the current global
124
+ * state (no matter "initialState" flag), if "undefined" is stored there.
125
+ * @return Retrieved value.
126
+ */
127
+
128
+ // .get() without arguments just falls back to .getEntireState().
129
+ // This variant attempts to automatically resolve and check the type of value
130
+ // at the given path, as precise as the actual state and path types permit.
131
+ // If the automatic path resolution is not possible, the ValueT fallsback
132
+ // to `never` (or to `undefined` in some cases), effectively forbidding
133
+ // to use this .get() variant.
134
+ // This variant is not callable by default (without generic arguments),
135
+ // otherwise it allows to set the correct ValueT directly.
136
+ get(path, opts) {
137
+ if (isNil(path)) {
138
+ const res = this.getEntireState(opts);
139
+ return res;
140
+ }
141
+ const state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
142
+ let res = get(state, path);
143
+ if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return res;
144
+ const iv = opts.initialValue;
145
+ res = isFunction(iv) ? iv() : iv;
146
+ if (!(opts !== null && opts !== void 0 && opts.initialState) || this.get(path) === undefined) {
147
+ this.set(path, res);
148
+ }
149
+ return res;
150
+ }
151
+
152
+ /**
153
+ * Writes the `value` to given global state `path`.
154
+ * @param path Dot-delimitered state path. If not given, entire
155
+ * global state content is replaced by the `value`.
156
+ * @param value The value.
157
+ * @return Given `value` itself.
158
+ */
159
+
160
+ // This variant attempts automatic value type resolution & checking.
161
+ // This variant is disabled by default, otherwise allows to give
162
+ // expected value type explicitly.
163
+ set(path, value) {
164
+ if (isNil(path)) return this.setEntireState(value);
165
+ if (value !== this.get(path)) {
166
+ const root = {
167
+ state: _classPrivateFieldGet(this, _currentState)
168
+ };
169
+ let segIdx = 0;
170
+ let pos = root;
171
+ const pathSegments = toPath(`state.${path}`);
172
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
173
+ const seg = pathSegments[segIdx];
174
+ const next = pos[seg];
175
+ if (Array.isArray(next)) pos[seg] = [...next];else if (isObject(next)) pos[seg] = {
176
+ ...next
177
+ };else {
178
+ // We arrived to a state sub-segment, where the remaining part of
179
+ // the update path does not exist yet. We rely on lodash's set()
180
+ // function to create the remaining path, and set the value.
181
+ set(pos, pathSegments.slice(segIdx), value);
182
+ break;
183
+ }
184
+ pos = pos[seg];
185
+ }
186
+ if (segIdx === pathSegments.length - 1) {
187
+ pos[pathSegments[segIdx]] = value;
188
+ }
189
+ _classPrivateFieldSet(this, _currentState, root.state);
190
+ this.notifyStateUpdate(path, value);
191
+ }
192
+ return value;
193
+ }
194
+
195
+ /**
196
+ * Unsubscribes `callback` from watching state updates; no operation if
197
+ * `callback` is not subscribed to the state updates.
198
+ * @param callback
199
+ * @throws if {@link SsrContext} is attached to the state instance: the state
200
+ * watching functionality is intended for client-side (non-SSR) only.
201
+ */
202
+ unWatch(callback) {
203
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
204
+ const watchers = _classPrivateFieldGet(this, _watchers);
205
+ const pos = watchers.indexOf(callback);
206
+ if (pos >= 0) {
207
+ watchers[pos] = watchers[watchers.length - 1];
208
+ watchers.pop();
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Subscribes `callback` to watch state updates; no operation if
214
+ * `callback` is already subscribed to this state instance.
215
+ * @param callback It will be called without any arguments every
216
+ * time the state content changes (note, howhever, separate state updates can
217
+ * be applied to the state at once, and watching callbacks will be called once
218
+ * after such bulk update).
219
+ * @throws if {@link SsrContext} is attached to the state instance: the state
220
+ * watching functionality is intended for client-side (non-SSR) only.
221
+ */
222
+ watch(callback) {
223
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
224
+ const watchers = _classPrivateFieldGet(this, _watchers);
225
+ if (watchers.indexOf(callback) < 0) {
226
+ watchers.push(callback);
227
+ }
228
+ }
229
+ }
230
+ //# sourceMappingURL=GlobalState.js.map