@dr.pogodin/react-global-state 0.8.3 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/module/GlobalState.js +156 -146
- package/build/module/GlobalState.js.map +1 -1
- package/build/module/GlobalStateProvider.js +21 -36
- package/build/module/GlobalStateProvider.js.map +1 -1
- package/build/module/index.js +1 -8
- package/build/module/index.js.map +1 -1
- package/build/module/useAsyncCollection.js +5 -6
- package/build/module/useAsyncCollection.js.map +1 -1
- package/build/module/useAsyncData.js +75 -117
- package/build/module/useAsyncData.js.map +1 -1
- package/build/module/useGlobalState.js +41 -64
- package/build/module/useGlobalState.js.map +1 -1
- package/build/module/utils.js.map +1 -1
- package/build/node/GlobalState.js +83 -81
- package/build/node/GlobalState.js.map +1 -1
- package/build/node/GlobalStateProvider.js +9 -25
- package/build/node/GlobalStateProvider.js.map +1 -1
- package/build/node/index.js +0 -8
- package/build/node/index.js.map +1 -1
- package/build/node/useAsyncCollection.js +0 -3
- package/build/node/useAsyncCollection.js.map +1 -1
- package/build/node/useAsyncData.js +25 -36
- package/build/node/useAsyncData.js.map +1 -1
- package/build/node/useGlobalState.js +36 -54
- package/build/node/useGlobalState.js.map +1 -1
- package/build/node/utils.js +0 -2
- package/build/node/utils.js.map +1 -1
- package/package.json +21 -21
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
|
|
2
|
-
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
3
|
-
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
4
|
-
import _regeneratorRuntime from "@babel/runtime/regenerator";
|
|
5
|
-
|
|
6
|
-
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
|
|
7
|
-
|
|
8
|
-
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
|
|
9
|
-
|
|
10
1
|
/**
|
|
11
2
|
* Loads and uses async data into the GlobalState path.
|
|
12
3
|
*/
|
|
4
|
+
|
|
13
5
|
import { cloneDeep } from 'lodash';
|
|
14
6
|
import { useEffect } from 'react';
|
|
15
7
|
import { v4 as uuid } from 'uuid';
|
|
16
8
|
import { getGlobalState } from "./GlobalStateProvider";
|
|
17
9
|
import useGlobalState from "./useGlobalState";
|
|
18
10
|
import { isDebugMode } from "./utils";
|
|
19
|
-
|
|
11
|
+
const DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
|
|
20
12
|
|
|
21
13
|
/**
|
|
22
14
|
* Executes the data loading operation.
|
|
@@ -32,10 +24,41 @@ var DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
|
|
|
32
24
|
* @return {Promise} Resolves once the operation is done.
|
|
33
25
|
* @ignore
|
|
34
26
|
*/
|
|
27
|
+
async function load(path, loader, globalState, oldData) {
|
|
28
|
+
let opIdPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'C';
|
|
29
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
30
|
+
/* eslint-disable no-console */
|
|
31
|
+
console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
|
|
32
|
+
/* eslint-enable no-console */
|
|
33
|
+
}
|
|
35
34
|
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
const operationId = opIdPrefix + uuid();
|
|
36
|
+
const operationIdPath = path ? `${path}.operationId` : 'operationId';
|
|
37
|
+
globalState.set(operationIdPath, operationId);
|
|
38
|
+
const data = await loader(oldData || globalState.get(path).data);
|
|
39
|
+
const state = globalState.get(path);
|
|
40
|
+
if (operationId === state.operationId) {
|
|
41
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
42
|
+
/* eslint-disable no-console */
|
|
43
|
+
console.groupCollapsed(`ReactGlobalState: useAsyncData data (re-)loaded. Path: "${path || ''}"`);
|
|
44
|
+
console.log('Data:', cloneDeep(data));
|
|
45
|
+
/* eslint-enable no-console */
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
globalState.set(path, {
|
|
49
|
+
...state,
|
|
50
|
+
data,
|
|
51
|
+
operationId: '',
|
|
52
|
+
timestamp: Date.now()
|
|
53
|
+
});
|
|
54
|
+
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
55
|
+
/* eslint-disable no-console */
|
|
56
|
+
console.groupEnd();
|
|
57
|
+
/* eslint-enable no-console */
|
|
58
|
+
}
|
|
59
|
+
}
|
|
38
60
|
}
|
|
61
|
+
|
|
39
62
|
/**
|
|
40
63
|
* Resolves asynchronous data, and stores them at given `path` of global
|
|
41
64
|
* state. When multiple components rely on asynchronous data at the same `path`,
|
|
@@ -87,92 +110,28 @@ function load(_x, _x2, _x3, _x4) {
|
|
|
87
110
|
* _e.g._ {@link useGlobalState}, but doing so you may interfere with related
|
|
88
111
|
* `useAsyncData()` hooks logic.
|
|
89
112
|
*/
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
function _load() {
|
|
93
|
-
_load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(path, loader, globalState, oldData) {
|
|
94
|
-
var opIdPrefix,
|
|
95
|
-
operationId,
|
|
96
|
-
operationIdPath,
|
|
97
|
-
data,
|
|
98
|
-
state,
|
|
99
|
-
_args = arguments;
|
|
100
|
-
return _regeneratorRuntime.wrap(function _callee$(_context) {
|
|
101
|
-
while (1) {
|
|
102
|
-
switch (_context.prev = _context.next) {
|
|
103
|
-
case 0:
|
|
104
|
-
opIdPrefix = _args.length > 4 && _args[4] !== undefined ? _args[4] : 'C';
|
|
105
|
-
|
|
106
|
-
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
107
|
-
/* eslint-disable no-console */
|
|
108
|
-
console.log("ReactGlobalState: useAsyncData data (re-)loading. Path: \"".concat(path || '', "\""));
|
|
109
|
-
/* eslint-enable no-console */
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
operationId = opIdPrefix + uuid();
|
|
113
|
-
operationIdPath = path ? "".concat(path, ".operationId") : 'operationId';
|
|
114
|
-
globalState.set(operationIdPath, operationId);
|
|
115
|
-
_context.next = 7;
|
|
116
|
-
return loader(oldData || globalState.get(path).data);
|
|
117
|
-
|
|
118
|
-
case 7:
|
|
119
|
-
data = _context.sent;
|
|
120
|
-
state = globalState.get(path);
|
|
121
|
-
|
|
122
|
-
if (operationId === state.operationId) {
|
|
123
|
-
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
124
|
-
/* eslint-disable no-console */
|
|
125
|
-
console.groupCollapsed("ReactGlobalState: useAsyncData data (re-)loaded. Path: \"".concat(path || '', "\""));
|
|
126
|
-
console.log('Data:', cloneDeep(data));
|
|
127
|
-
/* eslint-enable no-console */
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
globalState.set(path, _objectSpread(_objectSpread({}, state), {}, {
|
|
131
|
-
data: data,
|
|
132
|
-
operationId: '',
|
|
133
|
-
timestamp: Date.now()
|
|
134
|
-
}));
|
|
135
|
-
|
|
136
|
-
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
137
|
-
/* eslint-disable no-console */
|
|
138
|
-
console.groupEnd();
|
|
139
|
-
/* eslint-enable no-console */
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
case 10:
|
|
144
|
-
case "end":
|
|
145
|
-
return _context.stop();
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}, _callee);
|
|
149
|
-
}));
|
|
150
|
-
return _load.apply(this, arguments);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
113
|
export default function useAsyncData(path, loader) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
114
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
115
|
+
let {
|
|
116
|
+
garbageCollectAge,
|
|
117
|
+
maxage,
|
|
118
|
+
refreshAge
|
|
119
|
+
} = options;
|
|
158
120
|
if (maxage === undefined) maxage = DEFAULT_MAXAGE;
|
|
159
121
|
if (refreshAge === undefined) refreshAge = maxage;
|
|
160
|
-
if (garbageCollectAge === undefined) garbageCollectAge = maxage;
|
|
161
|
-
// because that way we'll have issues with SSR (see details below).
|
|
122
|
+
if (garbageCollectAge === undefined) garbageCollectAge = maxage;
|
|
162
123
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
124
|
+
// Note: here we can't depend on useGlobalState() to init the initial value,
|
|
125
|
+
// because that way we'll have issues with SSR (see details below).
|
|
126
|
+
const globalState = getGlobalState();
|
|
127
|
+
const state = globalState.get(path, {
|
|
128
|
+
initialValue: {
|
|
168
129
|
data: null,
|
|
169
130
|
numRefs: 0,
|
|
170
131
|
operationId: '',
|
|
171
132
|
timestamp: 0
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
}
|
|
175
|
-
|
|
133
|
+
}
|
|
134
|
+
});
|
|
176
135
|
if (globalState.ssrContext && !options.noSSR) {
|
|
177
136
|
if (!state.timestamp && !state.operationId) {
|
|
178
137
|
globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
|
|
@@ -187,58 +146,57 @@ export default function useAsyncData(path, loader) {
|
|
|
187
146
|
//
|
|
188
147
|
// TODO: Though, maybe there is a way to refactor it into a cleaner code.
|
|
189
148
|
// The same applies to other useEffect() hooks below.
|
|
190
|
-
useEffect(
|
|
149
|
+
useEffect(() => {
|
|
191
150
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
192
|
-
|
|
193
|
-
|
|
151
|
+
const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
|
|
152
|
+
const numRefs = globalState.get(numRefsPath);
|
|
194
153
|
globalState.set(numRefsPath, numRefs + 1);
|
|
195
|
-
return
|
|
196
|
-
|
|
197
|
-
|
|
154
|
+
return () => {
|
|
155
|
+
const state2 = globalState.get(path);
|
|
198
156
|
if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
|
|
199
157
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
200
158
|
/* eslint-disable no-console */
|
|
201
|
-
console.log(
|
|
159
|
+
console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
|
|
202
160
|
/* eslint-enable no-console */
|
|
203
161
|
}
|
|
204
162
|
|
|
205
|
-
globalState.set(path,
|
|
163
|
+
globalState.set(path, {
|
|
164
|
+
...state2,
|
|
206
165
|
data: null,
|
|
207
166
|
numRefs: 0,
|
|
208
167
|
timestamp: 0
|
|
209
|
-
})
|
|
168
|
+
});
|
|
210
169
|
} else globalState.set(numRefsPath, state2.numRefs - 1);
|
|
211
170
|
};
|
|
212
|
-
}, [garbageCollectAge, globalState, path]);
|
|
171
|
+
}, [garbageCollectAge, globalState, path]);
|
|
172
|
+
|
|
173
|
+
// Note: a bunch of Rules of Hooks ignored belows because in our very
|
|
213
174
|
// special case the otherwise wrong behavior is actually what we need.
|
|
214
|
-
// Data loading and refreshing.
|
|
215
175
|
|
|
216
|
-
|
|
217
|
-
|
|
176
|
+
// Data loading and refreshing.
|
|
177
|
+
let loadTriggered = false;
|
|
178
|
+
useEffect(() => {
|
|
218
179
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
219
|
-
|
|
220
|
-
|
|
180
|
+
const state2 = globalState.get(path);
|
|
221
181
|
if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
|
|
222
182
|
load(path, loader, globalState, state2.data);
|
|
223
183
|
loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
|
|
224
184
|
}
|
|
225
185
|
});
|
|
226
|
-
|
|
227
|
-
|
|
186
|
+
|
|
187
|
+
const deps = options.deps || [];
|
|
188
|
+
useEffect(() => {
|
|
228
189
|
// eslint-disable-line react-hooks/rules-of-hooks
|
|
229
190
|
if (!loadTriggered && deps.length) load(path, loader, globalState);
|
|
230
191
|
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
|
|
231
|
-
}
|
|
232
|
-
// here, after the possible initialization of the loading operation, to take
|
|
233
|
-
// into effect the resulting loading state. This mostly ensures the correct
|
|
234
|
-
// SSR in the edge case when the loading starts, but times out, and incomplete
|
|
235
|
-
// render has to be served.
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
var _useGlobalState = useGlobalState(path),
|
|
239
|
-
_useGlobalState2 = _slicedToArray(_useGlobalState, 1),
|
|
240
|
-
localState = _useGlobalState2[0];
|
|
192
|
+
}
|
|
241
193
|
|
|
194
|
+
const [localState] = useGlobalState(path, {
|
|
195
|
+
data: null,
|
|
196
|
+
numRefs: 0,
|
|
197
|
+
operationId: '',
|
|
198
|
+
timestamp: 0
|
|
199
|
+
});
|
|
242
200
|
return {
|
|
243
201
|
data: maxage < Date.now() - localState.timestamp ? null : localState.data,
|
|
244
202
|
loading: Boolean(localState.operationId),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/useAsyncData.js"],"names":["cloneDeep","useEffect","v4","uuid","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","get","data","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","loading","Boolean"],"mappings":";;;;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DK,CAwDK;AACX,GAnFD,CAqFA;AACA;AACA;AACA;AACA;;;AACA,wBAAqBxC,cAAc,CAACI,IAAD,CAAnC;AAAA;AAAA,MAAOsC,UAAP;;AAEA,SAAO;AACLxB,IAAAA,IAAI,EAAEU,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAamB,UAAU,CAACrB,SAAjC,GAA6C,IAA7C,GAAoDqB,UAAU,CAACxB,IADhE;AAELyB,IAAAA,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC5B,WAAZ,CAFX;AAGLO,IAAAA,SAAS,EAAEqB,UAAU,CAACrB;AAHjB,GAAP;AAKD","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 { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [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 {string} [opIdPrefix='C'] 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 {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\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(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(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(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 {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} 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 {object} [options] Additional options.\n * @param {any[]} [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 {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] 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 {number} [options.maxage=5 x 60 x 1000] 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 {number} [options.refreshAge=maxage] 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 {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) 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 let state = globalState.get(path);\n if (state === undefined) {\n state = {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n globalState.set(path, state);\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(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\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(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(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 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === '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);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n // Note: this subscription to updates of the global state segment must be\n // here, after the possible initialization of the loading operation, to take\n // into effect the resulting loading state. This mostly ensures the correct\n // SSR in the edge case when the loading starts, but times out, and incomplete\n // render has to be served.\n const [localState] = useGlobalState(path);\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"],"file":"useAsyncData.js"}
|
|
1
|
+
{"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationId","operationIdPath","set","data","get","state","groupCollapsed","timestamp","Date","now","groupEnd","useAsyncData","options","garbageCollectAge","maxage","refreshAge","undefined","initialValue","numRefs","ssrContext","noSSR","pending","push","numRefsPath","state2","loadTriggered","charAt","deps","length","localState","loading","Boolean"],"sources":["../../src/useAsyncData.js"],"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 { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\nimport { isDebugMode } from './utils';\n\nconst DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.\n\n/**\n * Executes the data loading operation.\n * @param {string} path Data segment path inside the global state.\n * @param {function} loader Data loader.\n * @param {GlobalState} globalState The global state instance.\n * @param {any} [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 {string} [opIdPrefix='C'] 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 {Promise} Resolves once the operation is done.\n * @ignore\n */\nasync function load(path, loader, globalState, oldData, opIdPrefix = 'C') {\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(operationIdPath, operationId);\n const data = await loader(oldData || globalState.get(path).data);\n const state = globalState.get(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(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 {string} path Dot-delimitered state path, where data envelop is\n * stored.\n * @param {AsyncDataLoader} 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 {object} [options] Additional options.\n * @param {any[]} [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 {boolean} [options.noSSR] If `true`, this hook won't load data during\n * server-side rendering.\n * @param {number} [options.garbageCollectAge=maxage] 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 {number} [options.maxage=5 x 60 x 1000] 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 {number} [options.refreshAge=maxage] 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 {{\n * data: any,\n * loading: boolean,\n * timestamp: number\n * }} Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelope}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\nexport default function useAsyncData(\n path,\n loader,\n options = {},\n) {\n let { garbageCollectAge, maxage, refreshAge } = options;\n if (maxage === undefined) maxage = DEFAULT_MAXAGE;\n if (refreshAge === undefined) refreshAge = maxage;\n if (garbageCollectAge === undefined) 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(path, {\n initialValue: {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\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(numRefsPath);\n globalState.set(numRefsPath, numRefs + 1);\n return () => {\n const state2 = globalState.get(path);\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(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set(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 = globalState.get(path);\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt() === '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);\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState(path, {\n data: null,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\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"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,cAAc;AACvB,OAAOC,cAAc;AACrB,SAASC,WAAW;AAEpB,MAAMC,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,IAAI,CAACC,IAAI,EAAEC,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAoB;EAAA,IAAlBC,UAAU,uEAAG,GAAG;EACtE,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAIV,WAAW,EAAE,EAAE;IAC1D;IACAW,OAAO,CAACC,GAAG,CACR,4DAA2DT,IAAI,IAAI,EAAG,GAAE,CAC1E;IACD;EACF;;EACA,MAAMU,WAAW,GAAGN,UAAU,GAAGV,IAAI,EAAE;EACvC,MAAMiB,eAAe,GAAGX,IAAI,GAAI,GAAEA,IAAK,cAAa,GAAG,aAAa;EACpEE,WAAW,CAACU,GAAG,CAACD,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AG3C,cAAc,CAACI,IAAI,EAAE;IACxCa,IAAI,EAAE,IAAI;IACVe,OAAO,EAAE,CAAC;IACVlB,WAAW,EAAE,EAAE;IACfO,SAAS,EAAE;EACb,CAAC,CAAC;EAEF,OAAO;IACLJ,IAAI,EAAEW,MAAM,GAAGN,IAAI,CAACC,GAAG,EAAE,GAAGoB,UAAU,CAACtB,SAAS,GAAG,IAAI,GAAGsB,UAAU,CAAC1B,IAAI;IACzE2B,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC7B,WAAW,CAAC;IACxCO,SAAS,EAAEsB,UAAU,CAACtB;EACxB,CAAC;AACH"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
|
|
2
1
|
// Hook for updates of global state.
|
|
2
|
+
|
|
3
3
|
import { cloneDeep, isFunction } from 'lodash';
|
|
4
|
-
import { useEffect, useRef,
|
|
4
|
+
import { useEffect, useRef, useSyncExternalStore } from 'react';
|
|
5
5
|
import { getGlobalState } from "./GlobalStateProvider";
|
|
6
6
|
import { isDebugMode } from "./utils";
|
|
7
|
+
|
|
7
8
|
/**
|
|
8
9
|
* The primary hook for interacting with the global state, modeled after
|
|
9
10
|
* the standard React's
|
|
@@ -54,79 +55,55 @@ import { isDebugMode } from "./utils";
|
|
|
54
55
|
* Also, similar to the standard React's state setters, `setValue()` is
|
|
55
56
|
* stable function: it does not change between component re-renders.
|
|
56
57
|
*/
|
|
57
|
-
|
|
58
58
|
export default function useGlobalState(path, initialValue) {
|
|
59
|
-
|
|
60
|
-
var state = globalState.get(path);
|
|
61
|
-
|
|
62
|
-
if (state === undefined && initialValue !== undefined) {
|
|
63
|
-
var value = isFunction(initialValue) ? initialValue() : initialValue;
|
|
64
|
-
state = globalState.set(path, value);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
var _useState = useState(function () {
|
|
68
|
-
return state;
|
|
69
|
-
}),
|
|
70
|
-
_useState2 = _slicedToArray(_useState, 2),
|
|
71
|
-
localState = _useState2[0],
|
|
72
|
-
setLocalState = _useState2[1];
|
|
73
|
-
|
|
74
|
-
useEffect(function () {
|
|
75
|
-
// Note: the "callback.active" flag below is needed to workaround the issue
|
|
76
|
-
// https://github.com/birdofpreyru/react-global-state/issues/33,
|
|
77
|
-
// which, unfortunately, I am not able to reproduce in test environment,
|
|
78
|
-
// but I definitely seen it in the wild.
|
|
79
|
-
var callback = function callback() {
|
|
80
|
-
if (callback.active) {
|
|
81
|
-
var newState = globalState.get(path);
|
|
82
|
-
if (newState !== localState) setLocalState(function () {
|
|
83
|
-
return newState;
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
callback.active = true;
|
|
89
|
-
globalState.watch(callback);
|
|
90
|
-
callback();
|
|
91
|
-
return function () {
|
|
92
|
-
delete callback.active;
|
|
93
|
-
globalState.unWatch(callback);
|
|
94
|
-
};
|
|
95
|
-
}, [globalState, localState, path]);
|
|
96
|
-
var ref = useRef();
|
|
97
|
-
|
|
59
|
+
const ref = useRef();
|
|
98
60
|
if (!ref.current) {
|
|
99
61
|
ref.current = {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
62
|
+
callbacks: [],
|
|
63
|
+
setter: value => {
|
|
64
|
+
const rc = ref.current;
|
|
65
|
+
const newState = isFunction(value) ? value(rc.state) : value;
|
|
105
66
|
if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
|
|
106
67
|
/* eslint-disable no-console */
|
|
107
|
-
console.groupCollapsed(
|
|
108
|
-
console.log('New value:', cloneDeep(
|
|
68
|
+
console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
|
|
69
|
+
console.log('New value:', cloneDeep(newState));
|
|
109
70
|
console.groupEnd();
|
|
110
71
|
/* eslint-enable no-console */
|
|
111
72
|
}
|
|
112
73
|
|
|
113
|
-
globalState.set(
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
}
|
|
74
|
+
rc.globalState.set(rc.path, newState);
|
|
75
|
+
},
|
|
76
|
+
watcher: () => {
|
|
77
|
+
const rc = ref.current;
|
|
78
|
+
const state = rc.globalState.get(rc.path);
|
|
79
|
+
if (state !== rc.state) {
|
|
80
|
+
for (let i = 0; i < rc.callbacks.length; ++i) {
|
|
81
|
+
rc.callbacks[i]();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
123
84
|
}
|
|
124
85
|
};
|
|
125
|
-
} else {
|
|
126
|
-
ref.current.localState = localState;
|
|
127
|
-
ref.current.path = path;
|
|
128
86
|
}
|
|
129
|
-
|
|
130
|
-
|
|
87
|
+
const rc = ref.current;
|
|
88
|
+
const globalState = getGlobalState();
|
|
89
|
+
rc.globalState = globalState;
|
|
90
|
+
rc.path = path;
|
|
91
|
+
rc.state = useSyncExternalStore(cb => {
|
|
92
|
+
rc.callbacks.push(cb);
|
|
93
|
+
}, () => rc.globalState.get(rc.path, {
|
|
94
|
+
initialValue
|
|
95
|
+
}), () => rc.globalState.get(rc.path, {
|
|
96
|
+
initialValue,
|
|
97
|
+
initialState: true
|
|
98
|
+
}));
|
|
99
|
+
useEffect(() => {
|
|
100
|
+
globalState.watch(rc.watcher);
|
|
101
|
+
rc.watcher();
|
|
102
|
+
return () => globalState.unWatch(rc.watcher);
|
|
103
|
+
}, [globalState, rc]);
|
|
104
|
+
useEffect(() => {
|
|
105
|
+
rc.watcher();
|
|
106
|
+
}, [path, rc]);
|
|
107
|
+
return [rc.state, rc.setter];
|
|
131
108
|
}
|
|
132
109
|
//# sourceMappingURL=useGlobalState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"useGlobalState.js","names":["cloneDeep","isFunction","useEffect","useRef","useSyncExternalStore","getGlobalState","isDebugMode","useGlobalState","path","initialValue","ref","current","callbacks","setter","value","rc","newState","state","process","env","NODE_ENV","console","groupCollapsed","log","groupEnd","globalState","set","watcher","get","i","length","cb","push","initialState","watch","unWatch"],"sources":["../../src/useGlobalState.js"],"sourcesContent":["// Hook for updates of global state.\n\nimport { cloneDeep, isFunction } from 'lodash';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport { isDebugMode } from './utils';\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 {string} [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 {any} [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 {Array} 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 */\nexport default function useGlobalState(path, initialValue) {\n const ref = useRef();\n if (!ref.current) {\n ref.current = {\n callbacks: [],\n setter: (value) => {\n const rc = ref.current;\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(rc.path, newState);\n },\n watcher: () => {\n const rc = ref.current;\n const state = rc.globalState.get(rc.path);\n if (state !== rc.state) {\n for (let i = 0; i < rc.callbacks.length; ++i) {\n rc.callbacks[i]();\n }\n }\n },\n };\n }\n\n const rc = ref.current;\n const globalState = getGlobalState();\n rc.globalState = globalState;\n rc.path = path;\n\n rc.state = useSyncExternalStore(\n (cb) => { rc.callbacks.push(cb); },\n () => rc.globalState.get(rc.path, { initialValue }),\n () => rc.globalState.get(rc.path, { initialValue, initialState: true }),\n );\n\n useEffect(() => {\n globalState.watch(rc.watcher);\n rc.watcher();\n return () => globalState.unWatch(rc.watcher);\n }, [globalState, rc]);\n\n useEffect(() => {\n rc.watcher();\n }, [path, rc]);\n\n return [rc.state, rc.setter];\n}\n"],"mappings":"AAAA;;AAEA,SAASA,SAAS,EAAEC,UAAU,QAAQ,QAAQ;AAC9C,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AAE/D,SAASC,cAAc;AACvB,SAASC,WAAW;;AAEpB;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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,CAAC,EAAE;UACnB;QACF;MACF;IACF,CAAC;EACH;EAEA,MAAMd,EAAE,GAAGL,GAAG,CAACC,OAAO;EACtB,MAAMc,WAAW,GAAGpB,cAAc,EAAE;EACpCU,EAAE,CAACU,WAAW,GAAGA,WAAW;EAC5BV,EAAE,CAACP,IAAI,GAAGA,IAAI;EAEdO,EAAE,CAACE,KAAK,GAAGb,oBAAoB,CAC5B2B,EAAE,IAAK;IAAEhB,EAAE,CAACH,SAAS,CAACoB,IAAI,CAACD,EAAE,CAAC;EAAE,CAAC,EAClC,MAAMhB,EAAE,CAACU,WAAW,CAACG,GAAG,CAACb,EAAE,CAACP,IAAI,EAAE;IAAEC;EAAa,CAAC,CAAC,EACnD,MAAMM,EAAE,CAACU,WAAW,CAACG,GAAG,CAACb,EAAE,CAACP,IAAI,EAAE;IAAEC,YAAY;IAAEwB,YAAY,EAAE;EAAK,CAAC,CAAC,CACxE;EAED/B,SAAS,CAAC,MAAM;IACduB,WAAW,CAACS,KAAK,CAACnB,EAAE,CAACY,OAAO,CAAC;IAC7BZ,EAAE,CAACY,OAAO,EAAE;IACZ,OAAO,MAAMF,WAAW,CAACU,OAAO,CAACpB,EAAE,CAACY,OAAO,CAAC;EAC9C,CAAC,EAAE,CAACF,WAAW,EAAEV,EAAE,CAAC,CAAC;EAErBb,SAAS,CAAC,MAAM;IACda,EAAE,CAACY,OAAO,EAAE;EACd,CAAC,EAAE,CAACnB,IAAI,EAAEO,EAAE,CAAC,CAAC;EAEd,OAAO,CAACA,EAAE,CAACE,KAAK,EAAEF,EAAE,CAACF,MAAM,CAAC;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"utils.js","names":["isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error"],"sources":["../../src/utils.js"],"sourcesContent":["// Auxiliary stuff.\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 {boolean}\n * @ignore\n */\nexport function isDebugMode() {\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\nexport default null;\n"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,WAAW,GAAG;EAC5B,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;AAEA,eAAe,IAAI"}
|