@dr.pogodin/react-global-state 0.9.0 → 0.9.2

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.
@@ -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
- var DEFAULT_MAXAGE = 5 * 60 * 1000; // 5 minutes.
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
- function load(_x, _x2, _x3, _x4) {
37
- return _load.apply(this, arguments);
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,81 +110,21 @@ 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
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
155
- var garbageCollectAge = options.garbageCollectAge,
156
- maxage = options.maxage,
157
- refreshAge = options.refreshAge;
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; // Note: here we can't depend on useGlobalState() to init the initial value,
161
- // because that way we'll have issues with SSR (see details below).
122
+ if (garbageCollectAge === undefined) garbageCollectAge = maxage;
162
123
 
163
- var globalState = getGlobalState();
164
- var state = globalState.get(path, {
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, {
165
128
  initialValue: {
166
129
  data: null,
167
130
  numRefs: 0,
@@ -169,7 +132,6 @@ export default function useAsyncData(path, loader) {
169
132
  timestamp: 0
170
133
  }
171
134
  });
172
-
173
135
  if (globalState.ssrContext && !options.noSSR) {
174
136
  if (!state.timestamp && !state.operationId) {
175
137
  globalState.ssrContext.pending.push(load(path, loader, globalState, state.data, 'S'));
@@ -184,58 +146,57 @@ export default function useAsyncData(path, loader) {
184
146
  //
185
147
  // TODO: Though, maybe there is a way to refactor it into a cleaner code.
186
148
  // The same applies to other useEffect() hooks below.
187
- useEffect(function () {
149
+ useEffect(() => {
188
150
  // eslint-disable-line react-hooks/rules-of-hooks
189
- var numRefsPath = path ? "".concat(path, ".numRefs") : 'numRefs';
190
- var numRefs = globalState.get(numRefsPath);
151
+ const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
152
+ const numRefs = globalState.get(numRefsPath);
191
153
  globalState.set(numRefsPath, numRefs + 1);
192
- return function () {
193
- var state2 = globalState.get(path);
194
-
154
+ return () => {
155
+ const state2 = globalState.get(path);
195
156
  if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
196
157
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
197
158
  /* eslint-disable no-console */
198
- console.log("ReactGlobalState - useAsyncData garbage collected at path ".concat(path || ''));
159
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
199
160
  /* eslint-enable no-console */
200
161
  }
201
162
 
202
- globalState.set(path, _objectSpread(_objectSpread({}, state2), {}, {
163
+ globalState.set(path, {
164
+ ...state2,
203
165
  data: null,
204
166
  numRefs: 0,
205
167
  timestamp: 0
206
- }));
168
+ });
207
169
  } else globalState.set(numRefsPath, state2.numRefs - 1);
208
170
  };
209
- }, [garbageCollectAge, globalState, path]); // Note: a bunch of Rules of Hooks ignored belows because in our very
171
+ }, [garbageCollectAge, globalState, path]);
172
+
173
+ // Note: a bunch of Rules of Hooks ignored belows because in our very
210
174
  // special case the otherwise wrong behavior is actually what we need.
211
- // Data loading and refreshing.
212
175
 
213
- var loadTriggered = false;
214
- useEffect(function () {
176
+ // Data loading and refreshing.
177
+ let loadTriggered = false;
178
+ useEffect(() => {
215
179
  // eslint-disable-line react-hooks/rules-of-hooks
216
- var state2 = globalState.get(path);
217
-
180
+ const state2 = globalState.get(path);
218
181
  if (refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt() === 'S')) {
219
182
  load(path, loader, globalState, state2.data);
220
183
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
221
184
  }
222
185
  });
223
- var deps = options.deps || [];
224
- useEffect(function () {
186
+
187
+ const deps = options.deps || [];
188
+ useEffect(() => {
225
189
  // eslint-disable-line react-hooks/rules-of-hooks
226
190
  if (!loadTriggered && deps.length) load(path, loader, globalState);
227
191
  }, deps); // eslint-disable-line react-hooks/exhaustive-deps
228
192
  }
229
193
 
230
- var _useGlobalState = useGlobalState(path, {
194
+ const [localState] = useGlobalState(path, {
231
195
  data: null,
232
196
  numRefs: 0,
233
197
  operationId: '',
234
198
  timestamp: 0
235
- }),
236
- _useGlobalState2 = _slicedToArray(_useGlobalState, 1),
237
- localState = _useGlobalState2[0];
238
-
199
+ });
239
200
  return {
240
201
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
241
202
  loading: Boolean(localState.operationId),
@@ -1 +1 @@
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","get","data","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,SAAT,QAA0B,QAA1B;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,SAASC,EAAE,IAAIC,IAAf,QAA2B,MAA3B;AAEA,SAASC,cAAT;AACA,OAAOC,cAAP;AACA,SAASC,WAAT;AAEA,IAAMC,cAAc,GAAG,IAAI,EAAJ,GAAS,IAAhC,C,CAAsC;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;SACeC,I;;;AAsCf;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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,WAAf,EAA4BgC,MAAM,CAACpB,IAAnC,CAAJ;QACAqB,aAAa,GAAG,IAAhB,CAF+D,CAEzC;MACvB;IACF,CAPQ,CAAT;IASA,IAAME,IAAI,GAAGf,OAAO,CAACe,IAAR,IAAgB,EAA7B;IACA7C,SAAS,CAAC,YAAM;MAAE;MAChB,IAAI,CAAC2C,aAAD,IAAkBE,IAAI,CAACC,MAA3B,EAAmCvC,IAAI,CAACC,IAAD,EAAOC,MAAP,EAAeC,WAAf,CAAJ;IACpC,CAFQ,EAENmC,IAFM,CAAT,CAtDK,CAwDK;EACX;;EAED,sBAAqBzC,cAAc,CAACI,IAAD,EAAO;IACxCc,IAAI,EAAE,IADkC;IAExCc,OAAO,EAAE,CAF+B;IAGxClB,WAAW,EAAE,EAH2B;IAIxCO,SAAS,EAAE;EAJ6B,CAAP,CAAnC;EAAA;EAAA,IAAOsB,UAAP;;EAOA,OAAO;IACLzB,IAAI,EAAEU,MAAM,GAAGN,IAAI,CAACC,GAAL,KAAaoB,UAAU,CAACtB,SAAjC,GAA6C,IAA7C,GAAoDsB,UAAU,CAACzB,IADhE;IAEL0B,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC7B,WAAZ,CAFX;IAGLO,SAAS,EAAEsB,UAAU,CAACtB;EAHjB,CAAP;AAKD"}
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,eAAe,EAAED,WAAW,CAAC;EAC7C,MAAMG,IAAI,GAAG,MAAMZ,MAAM,CAACE,OAAO,IAAID,WAAW,CAACY,GAAG,CAACd,IAAI,CAAC,CAACa,IAAI,CA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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,8 +1,10 @@
1
1
  // Hook for updates of global state.
2
+
2
3
  import { cloneDeep, isFunction } from 'lodash';
3
4
  import { useEffect, useRef, useSyncExternalStore } from 'react';
4
5
  import { getGlobalState } from "./GlobalStateProvider";
5
6
  import { isDebugMode } from "./utils";
7
+
6
8
  /**
7
9
  * The primary hook for interacting with the global state, modeled after
8
10
  * the standard React's
@@ -53,20 +55,17 @@ import { isDebugMode } from "./utils";
53
55
  * Also, similar to the standard React's state setters, `setValue()` is
54
56
  * stable function: it does not change between component re-renders.
55
57
  */
56
-
57
58
  export default function useGlobalState(path, initialValue) {
58
- var ref = useRef();
59
-
59
+ const ref = useRef();
60
60
  if (!ref.current) {
61
61
  ref.current = {
62
62
  callbacks: [],
63
- setter: function setter(value) {
64
- var rc = ref.current;
65
- var newState = isFunction(value) ? value(rc.state) : value;
66
-
63
+ setter: value => {
64
+ const rc = ref.current;
65
+ const newState = isFunction(value) ? value(rc.state) : value;
67
66
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
68
67
  /* eslint-disable no-console */
69
- console.groupCollapsed("ReactGlobalState - useGlobalState setter triggered for path ".concat(rc.path || ''));
68
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path || ''}`);
70
69
  console.log('New value:', cloneDeep(newState));
71
70
  console.groupEnd();
72
71
  /* eslint-enable no-console */
@@ -74,43 +73,35 @@ export default function useGlobalState(path, initialValue) {
74
73
 
75
74
  rc.globalState.set(rc.path, newState);
76
75
  },
77
- watcher: function watcher() {
78
- var rc = ref.current;
79
- var state = rc.globalState.get(rc.path);
80
-
76
+ watcher: () => {
77
+ const rc = ref.current;
78
+ const state = rc.globalState.get(rc.path);
81
79
  if (state !== rc.state) {
82
- for (var i = 0; i < rc.callbacks.length; ++i) {
80
+ for (let i = 0; i < rc.callbacks.length; ++i) {
83
81
  rc.callbacks[i]();
84
82
  }
85
83
  }
86
84
  }
87
85
  };
88
86
  }
89
-
90
- var rc = ref.current;
91
- var globalState = getGlobalState();
87
+ const rc = ref.current;
88
+ const globalState = getGlobalState();
92
89
  rc.globalState = globalState;
93
90
  rc.path = path;
94
- rc.state = useSyncExternalStore(function (cb) {
91
+ rc.state = useSyncExternalStore(cb => {
95
92
  rc.callbacks.push(cb);
96
- }, function () {
97
- return rc.globalState.get(rc.path, {
98
- initialValue: initialValue
99
- });
100
- }, function () {
101
- return rc.globalState.get(rc.path, {
102
- initialValue: initialValue,
103
- initialState: true
104
- });
105
- });
106
- useEffect(function () {
93
+ }, () => rc.globalState.get(rc.path, {
94
+ initialValue
95
+ }), () => rc.globalState.get(rc.path, {
96
+ initialValue,
97
+ initialState: true
98
+ }));
99
+ useEffect(() => {
107
100
  globalState.watch(rc.watcher);
108
101
  rc.watcher();
109
- return function () {
110
- return globalState.unWatch(rc.watcher);
111
- };
102
+ return () => globalState.unWatch(rc.watcher);
112
103
  }, [globalState, rc]);
113
- useEffect(function () {
104
+ useEffect(() => {
114
105
  rc.watcher();
115
106
  }, [path, rc]);
116
107
  return [rc.state, rc.setter];
@@ -1 +1 @@
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,SAAT,EAAoBC,UAApB,QAAsC,QAAtC;AACA,SAASC,SAAT,EAAoBC,MAApB,EAA4BC,oBAA5B,QAAwD,OAAxD;AAEA,SAASC,cAAT;AACA,SAASC,WAAT;AAEA;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;;AACA,eAAe,SAASC,cAAT,CAAwBC,IAAxB,EAA8BC,YAA9B,EAA4C;EACzD,IAAMC,GAAG,GAAGP,MAA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IAAV;EAEAO,EAAE,CAACE,KAAH,GAAWb,oBAAoB,CAC7B,UAAC2B,EAAD,EAAQ;IAAEhB,EAAE,CAACH,SAAH,CAAaoB,IAAb,CAAkBD,EAAlB;EAAwB,CADL,EAE7B;IAAA,OAAMhB,EAAE,CAACU,WAAH,CAAeG,GAAf,CAAmBb,EAAE,CAACP,IAAtB,EAA4B;MAAEC,YAAY,EAAZA;IAAF,CAA5B,CAAN;EAAA,CAF6B,EAG7B;IAAA,OAAMM,EAAE,CAACU,WAAH,CAAeG,GAAf,CAAmBb,EAAE,CAACP,IAAtB,EAA4B;MAAEC,YAAY,EAAZA,YAAF;MAAgBwB,YAAY,EAAE;IAA9B,CAA5B,CAAN;EAAA,CAH6B,CAA/B;EAMA/B,SAAS,CAAC,YAAM;IACduB,WAAW,CAACS,KAAZ,CAAkBnB,EAAE,CAACY,OAArB;IACAZ,EAAE,CAACY,OAAH;IACA,OAAO;MAAA,OAAMF,WAAW,CAACU,OAAZ,CAAoBpB,EAAE,CAACY,OAAvB,CAAN;IAAA,CAAP;EACD,CAJQ,EAIN,CAACF,WAAD,EAAcV,EAAd,CAJM,CAAT;EAMAb,SAAS,CAAC,YAAM;IACda,EAAE,CAACY,OAAH;EACD,CAFQ,EAEN,CAACnB,IAAD,EAAOO,EAAP,CAFM,CAAT;EAIA,OAAO,CAACA,EAAE,CAACE,KAAJ,EAAWF,EAAE,CAACF,MAAd,CAAP;AACD"}
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;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,eAAe,SAASC,cAAc,CAACC,IAAI,EAAEC,YAAY,EAAE;EACzD,MAAMC,GAAG,GAAGP,MAAM,EAAE;EACpB,IAAI,CAACO,GA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K,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,"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,WAAT,GAAuB;EAC5B,IAAI;IACF,OAAOC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,IACF,CAAC,CAACF,OAAO,CAACC,GAAR,CAAYE,wBADnB;EAED,CAHD,CAGE,OAAOC,KAAP,EAAc;IACd,OAAO,KAAP;EACD;AACF;AAED,eAAe,IAAf"}
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"}
@@ -4,29 +4,24 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  var _lodash = require("lodash");
9
-
10
8
  var _utils = require("./utils");
11
-
12
9
  const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
13
-
14
10
  class GlobalState {
15
11
  #initialState;
16
12
  #nextNotifierId = null;
17
13
  #ssrContext;
18
14
  #currentState;
19
15
  #watchers = [];
16
+
20
17
  /**
21
18
  * Creates a new global state object.
22
19
  * @param {any} [initialState] Intial global state content.
23
20
  * @param {SsrContext} [ssrContext] Server-side rendering context.
24
21
  */
25
-
26
22
  constructor(initialState, ssrContext) {
27
23
  this.#currentState = initialState;
28
24
  this.#initialState = initialState;
29
-
30
25
  if (ssrContext) {
31
26
  /* eslint-disable no-param-reassign */
32
27
  ssrContext.dirty = false;
@@ -36,7 +31,6 @@ class GlobalState {
36
31
 
37
32
  this.#ssrContext = ssrContext;
38
33
  }
39
-
40
34
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
41
35
  /* eslint-disable no-console */
42
36
  let msg = 'New ReactGlobalState created';
@@ -47,6 +41,7 @@ class GlobalState {
47
41
  /* eslint-enable no-console */
48
42
  }
49
43
  }
44
+
50
45
  /**
51
46
  * Gets current or initial value at the specified "path" of the global state.
52
47
  * Allows to get the entire global state, and automatically set default value
@@ -62,22 +57,19 @@ class GlobalState {
62
57
  * state (no matter "initialState" flag), if "undefined" is stored there.
63
58
  * @return {any} Retrieved value.
64
59
  */
65
-
66
-
67
60
  get(path, {
68
61
  initialState,
69
62
  initialValue
70
63
  } = {}) {
71
64
  const state = initialState ? this.#initialState : this.#currentState;
72
65
  let value = (0, _lodash.isNil)(path) ? state : (0, _lodash.get)(state, path);
73
-
74
66
  if (value === undefined && initialValue !== undefined) {
75
67
  value = (0, _lodash.isFunction)(initialValue) ? initialValue() : initialValue;
76
68
  if (!initialState || this.get(path) === undefined) this.set(path, value);
77
69
  }
78
-
79
70
  return value;
80
71
  }
72
+
81
73
  /**
82
74
  * Writes the `value` to given global state `path`.
83
75
  * @param {string} [path] Dot-delimitered state path. If not given, entire
@@ -85,8 +77,6 @@ class GlobalState {
85
77
  * @param {any} value The value.
86
78
  * @return {any} Given `value` itself.
87
79
  */
88
-
89
-
90
80
  set(path, value) {
91
81
  if (value !== this.get(path)) {
92
82
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
@@ -103,11 +93,11 @@ class GlobalState {
103
93
  let segIdx = 0;
104
94
  let pos = root;
105
95
  const pathSegments = (0, _lodash.toPath)(`state.${path}`);
106
-
107
96
  for (; segIdx < pathSegments.length - 1; segIdx += 1) {
108
97
  const seg = pathSegments[segIdx];
109
98
  const next = pos[seg];
110
- if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = { ...next
99
+ if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
100
+ ...next
111
101
  };else {
112
102
  // We arrived to a state sub-segment, where the remaining part of
113
103
  // the update path does not exist yet. We rely on lodash's set()
@@ -117,14 +107,11 @@ class GlobalState {
117
107
  }
118
108
  pos = pos[seg];
119
109
  }
120
-
121
110
  if (segIdx === pathSegments.length - 1) {
122
111
  pos[pathSegments[segIdx]] = value;
123
112
  }
124
-
125
113
  this.#currentState = root.state;
126
114
  }
127
-
128
115
  if (this.#ssrContext) {
129
116
  this.#ssrContext.dirty = true;
130
117
  this.#ssrContext.state = this.#currentState;
@@ -134,7 +121,6 @@ class GlobalState {
134
121
  [...this.#watchers].forEach(w => w());
135
122
  });
136
123
  }
137
-
138
124
  if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
139
125
  /* eslint-disable no-console */
140
126
  console.log('New state:', (0, _lodash.cloneDeep)(this.#currentState));
@@ -145,6 +131,7 @@ class GlobalState {
145
131
 
146
132
  return value;
147
133
  }
134
+
148
135
  /**
149
136
  * Unsubscribes `callback` from watching state updates; no operation if
150
137
  * `callback` is not subscribed to the state updates.
@@ -152,22 +139,19 @@ class GlobalState {
152
139
  * @throws if {@link SsrContext} is attached to the state instance: the state
153
140
  * watching functionality is intended for client-side (non-SSR) only.
154
141
  */
155
-
156
-
157
142
  unWatch(callback) {
158
143
  if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
159
144
  const watchers = this.#watchers;
160
145
  const pos = watchers.indexOf(callback);
161
-
162
146
  if (pos >= 0) {
163
147
  watchers[pos] = watchers[watchers.length - 1];
164
148
  watchers.pop();
165
149
  }
166
150
  }
167
-
168
151
  get ssrContext() {
169
152
  return this.#ssrContext;
170
153
  }
154
+
171
155
  /**
172
156
  * Subscribes `callback` to watch state updates; no operation if
173
157
  * `callback` is already subscribed to this state instance.
@@ -178,18 +162,13 @@ class GlobalState {
178
162
  * @throws if {@link SsrContext} is attached to the state instance: the state
179
163
  * watching functionality is intended for client-side (non-SSR) only.
180
164
  */
181
-
182
-
183
165
  watch(callback) {
184
166
  if (this.#ssrContext) throw new Error(ERR_NO_SSR_WATCH);
185
167
  const watchers = this.#watchers;
186
-
187
168
  if (watchers.indexOf(callback) < 0) {
188
169
  watchers.push(callback);
189
170
  }
190
171
  }
191
-
192
172
  }
193
-
194
173
  exports.default = GlobalState;
195
174
  //# sourceMappingURL=GlobalState.js.map