@dr.pogodin/react-global-state 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,8 @@
1
- import _classPrivateFieldGet from "@babel/runtime/helpers/classPrivateFieldGet";
2
- import _classPrivateFieldSet from "@babel/runtime/helpers/classPrivateFieldSet";
3
1
  function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
4
2
  function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
3
+ function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
4
+ function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
5
+ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
5
6
  import { cloneDeep, get, isFunction, isObject, isNil, set, toPath } from 'lodash';
6
7
  import { isDebugMode } from "./utils";
7
8
  const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
@@ -17,37 +18,22 @@ export default class GlobalState {
17
18
  * @param ssrContext Server-side rendering context.
18
19
  */
19
20
  constructor(initialState, ssrContext) {
20
- _classPrivateFieldInitSpec(this, _dependencies, {
21
- writable: true,
22
- value: {}
23
- });
24
- _classPrivateFieldInitSpec(this, _initialState, {
25
- writable: true,
26
- value: void 0
27
- });
21
+ _classPrivateFieldInitSpec(this, _dependencies, {});
22
+ _classPrivateFieldInitSpec(this, _initialState, void 0);
28
23
  // TODO: It is tempting to replace watchers here by
29
24
  // Emitter from @dr.pogodin/js-utils, but we need to clone
30
25
  // current watchers for emitting later, and this is not something
31
26
  // Emitter supports right now.
32
- _classPrivateFieldInitSpec(this, _watchers, {
33
- writable: true,
34
- value: []
35
- });
36
- _classPrivateFieldInitSpec(this, _nextNotifierId, {
37
- writable: true,
38
- value: void 0
39
- });
40
- _classPrivateFieldInitSpec(this, _currentState, {
41
- writable: true,
42
- value: void 0
43
- });
44
- _classPrivateFieldSet(this, _currentState, initialState);
45
- _classPrivateFieldSet(this, _initialState, initialState);
27
+ _classPrivateFieldInitSpec(this, _watchers, []);
28
+ _classPrivateFieldInitSpec(this, _nextNotifierId, void 0);
29
+ _classPrivateFieldInitSpec(this, _currentState, void 0);
30
+ _classPrivateFieldSet(_currentState, this, initialState);
31
+ _classPrivateFieldSet(_initialState, this, initialState);
46
32
  if (ssrContext) {
47
33
  /* eslint-disable no-param-reassign */
48
34
  ssrContext.dirty = false;
49
35
  ssrContext.pending = [];
50
- ssrContext.state = _classPrivateFieldGet(this, _currentState);
36
+ ssrContext.state = _classPrivateFieldGet(_currentState, this);
51
37
  /* eslint-enable no-param-reassign */
52
38
 
53
39
  this.ssrContext = ssrContext;
@@ -67,7 +53,7 @@ export default class GlobalState {
67
53
  * Drops the record of dependencies, if any, for the given path.
68
54
  */
69
55
  dropDependencies(path) {
70
- delete _classPrivateFieldGet(this, _dependencies)[path];
56
+ delete _classPrivateFieldGet(_dependencies, this)[path];
71
57
  }
72
58
 
73
59
  /**
@@ -77,12 +63,12 @@ export default class GlobalState {
77
63
  * modified.
78
64
  */
79
65
  hasChangedDependencies(path, deps) {
80
- const prevDeps = _classPrivateFieldGet(this, _dependencies)[path];
66
+ const prevDeps = _classPrivateFieldGet(_dependencies, this)[path];
81
67
  let changed = !prevDeps || prevDeps.length !== deps.length;
82
68
  for (let i = 0; !changed && i < deps.length; ++i) {
83
69
  changed = prevDeps[i] !== deps[i];
84
70
  }
85
- _classPrivateFieldGet(this, _dependencies)[path] = Object.freeze(deps);
71
+ _classPrivateFieldGet(_dependencies, this)[path] = Object.freeze(deps);
86
72
  return changed;
87
73
  }
88
74
 
@@ -92,11 +78,11 @@ export default class GlobalState {
92
78
  * @param opts.initialValue
93
79
  */
94
80
  getEntireState(opts) {
95
- let state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
81
+ let state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(_initialState, this) : _classPrivateFieldGet(_currentState, this);
96
82
  if (state !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return state;
97
83
  const iv = opts.initialValue;
98
84
  state = isFunction(iv) ? iv() : iv;
99
- if (_classPrivateFieldGet(this, _currentState) === undefined) this.setEntireState(state);
85
+ if (_classPrivateFieldGet(_currentState, this) === undefined) this.setEntireState(state);
100
86
  return state;
101
87
  }
102
88
 
@@ -109,18 +95,17 @@ export default class GlobalState {
109
95
  const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
110
96
  console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
111
97
  console.log('New value:', cloneDeep(value));
112
- console.log('New state:', cloneDeep(_classPrivateFieldGet(this, _currentState)));
98
+ console.log('New state:', cloneDeep(_classPrivateFieldGet(_currentState, this)));
113
99
  console.groupEnd();
114
100
  /* eslint-enable no-console */
115
101
  }
116
-
117
102
  if (this.ssrContext) {
118
103
  this.ssrContext.dirty = true;
119
- this.ssrContext.state = _classPrivateFieldGet(this, _currentState);
120
- } else if (!_classPrivateFieldGet(this, _nextNotifierId)) {
121
- _classPrivateFieldSet(this, _nextNotifierId, setTimeout(() => {
122
- _classPrivateFieldSet(this, _nextNotifierId, undefined);
123
- const watchers = [..._classPrivateFieldGet(this, _watchers)];
104
+ this.ssrContext.state = _classPrivateFieldGet(_currentState, this);
105
+ } else if (!_classPrivateFieldGet(_nextNotifierId, this)) {
106
+ _classPrivateFieldSet(_nextNotifierId, this, setTimeout(() => {
107
+ _classPrivateFieldSet(_nextNotifierId, this, undefined);
108
+ const watchers = [..._classPrivateFieldGet(_watchers, this)];
124
109
  for (let i = 0; i < watchers.length; ++i) {
125
110
  watchers[i]();
126
111
  }
@@ -133,8 +118,8 @@ export default class GlobalState {
133
118
  * @param value
134
119
  */
135
120
  setEntireState(value) {
136
- if (_classPrivateFieldGet(this, _currentState) !== value) {
137
- _classPrivateFieldSet(this, _currentState, value);
121
+ if (_classPrivateFieldGet(_currentState, this) !== value) {
122
+ _classPrivateFieldSet(_currentState, this, value);
138
123
  this.notifyStateUpdate(null, value);
139
124
  }
140
125
  return value;
@@ -154,19 +139,22 @@ export default class GlobalState {
154
139
  */
155
140
 
156
141
  // .get() without arguments just falls back to .getEntireState().
142
+
157
143
  // This variant attempts to automatically resolve and check the type of value
158
144
  // at the given path, as precise as the actual state and path types permit.
159
145
  // If the automatic path resolution is not possible, the ValueT fallsback
160
146
  // to `never` (or to `undefined` in some cases), effectively forbidding
161
147
  // to use this .get() variant.
148
+
162
149
  // This variant is not callable by default (without generic arguments),
163
150
  // otherwise it allows to set the correct ValueT directly.
151
+
164
152
  get(path, opts) {
165
153
  if (isNil(path)) {
166
154
  const res = this.getEntireState(opts);
167
155
  return res;
168
156
  }
169
- const state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(this, _initialState) : _classPrivateFieldGet(this, _currentState);
157
+ const state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(_initialState, this) : _classPrivateFieldGet(_currentState, this);
170
158
  let res = get(state, path);
171
159
  if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return res;
172
160
  const iv = opts.initialValue;
@@ -186,13 +174,15 @@ export default class GlobalState {
186
174
  */
187
175
 
188
176
  // This variant attempts automatic value type resolution & checking.
177
+
189
178
  // This variant is disabled by default, otherwise allows to give
190
179
  // expected value type explicitly.
180
+
191
181
  set(path, value) {
192
182
  if (isNil(path)) return this.setEntireState(value);
193
183
  if (value !== this.get(path)) {
194
184
  const root = {
195
- state: _classPrivateFieldGet(this, _currentState)
185
+ state: _classPrivateFieldGet(_currentState, this)
196
186
  };
197
187
  let segIdx = 0;
198
188
  let pos = root;
@@ -214,7 +204,7 @@ export default class GlobalState {
214
204
  if (segIdx === pathSegments.length - 1) {
215
205
  pos[pathSegments[segIdx]] = value;
216
206
  }
217
- _classPrivateFieldSet(this, _currentState, root.state);
207
+ _classPrivateFieldSet(_currentState, this, root.state);
218
208
  this.notifyStateUpdate(path, value);
219
209
  }
220
210
  return value;
@@ -229,7 +219,7 @@ export default class GlobalState {
229
219
  */
230
220
  unWatch(callback) {
231
221
  if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
232
- const watchers = _classPrivateFieldGet(this, _watchers);
222
+ const watchers = _classPrivateFieldGet(_watchers, this);
233
223
  const pos = watchers.indexOf(callback);
234
224
  if (pos >= 0) {
235
225
  watchers[pos] = watchers[watchers.length - 1];
@@ -249,7 +239,7 @@ export default class GlobalState {
249
239
  */
250
240
  watch(callback) {
251
241
  if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
252
- const watchers = _classPrivateFieldGet(this, _watchers);
242
+ const watchers = _classPrivateFieldGet(_watchers, this);
253
243
  if (watchers.indexOf(callback) < 0) {
254
244
  watchers.push(callback);
255
245
  }
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalState.js","names":["cloneDeep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","writable","value","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #dependencies: { [key: string]: Readonly<any[]> } = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n */\n hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps[i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeep(value));\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;AAAA,SACEA,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GA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eep","get","isFunction","isObject","isNil","set","toPath","isDebugMode","ERR_NO_SSR_WATCH","_dependencies","WeakMap","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n cloneDeep,\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #dependencies: { [key: string]: Readonly<any[]> } = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeep(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string) {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n */\n hasChangedDependencies(path: string, deps: any[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps[i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeep(value));\n console.log('New state:', cloneDeep(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (let i = 0; i < watchers.length; ++i) {\n watchers[i]();\n }\n });\n }\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (isNil(path)) {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx];\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg];\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1];\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SACEA,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,GAAG,EACHC,MAAM,QACD,QAAQ;AAIf,SAOEC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,aAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,SAAA,oBAAAF,OAAA;AAAA,IAAAG,eAAA,oBAAAH,OAAA;AAAA,IAAAI,aAAA,oBAAAJ,OAAA;AAO1E,eAAe,MAAMK,WAAW,CAG9B;EAiBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAAAC,0BAAA,OAAAV,aAAA,EAtBkD,CAAC,CAAC;IAAAU,0BAAA,OAAAR,aAAA;IAItD;IACA;IACA;IACA;IAAAQ,0BAAA,OAAAP,SAAA,EACyB,EAAE;IAAAO,0BAAA,OAAAN,eAAA;IAAAM,0BAAA,OAAAL,aAAA;IAezBM,qBAAA,CAAAN,aAAA,MAAI,EAAiBG,YAAY;IACjCG,qBAAA,CAAAT,aAAA,MAAI,EAAiBM,YAAY;IAEjC,IAAIC,UAAU,EAAE;MACd;MACA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AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC/C,UAAU,EAAE,MAAM,IAAIgD,KAAK,CAAC1D,gBAAgB,CAAC;IAEtD,MAAM6C,QAAQ,GAAA7B,qBAAA,CAAAZ,SAAA,EAAG,IAAI,CAAU;IAC/B,IAAIyC,QAAQ,CAACc,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClCZ,QAAQ,CAACiB,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value","defaultProps"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n\nGlobalStateProvider.defaultProps = {\n children: undefined,\n};\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,UAAU,CAACK,OAAO,CAAC;EACvC;EACA,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAAA,EAIF;EAAA,IADzBC,sBAAsB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAE7B,MAAM;IAAEG;EAAW,CAAC,GAAGR,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACQ,UAAU,IAAIJ,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOM,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,mBAAmBA,CAAAC,IAAA,EAKzC;EAAA,IADA;IAAEC,QAAQ;IAAE,GAAGC;EAAoD,CAAC,GAAAF,IAAA;EAEpE,MAAMG,KAAK,GAAGlB,MAAM,CAAmC,CAAC;EACxD,IAAI,CAACkB,KAAK,CAACC,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIF,IAAI,IAAIA,IAAI,CAACG,UAAU,EAAE;MAC3C,IAAIH,IAAI,CAACG,UAAU,KAAK,IAAI,EAAEF,KAAK,CAACC,OAAO,GAAGd,cAAc,CAAC,CAAC,CAAC,KAC1Da,KAAK,CAACC,OAAO,GAAGF,IAAI,CAACG,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAER;MAAW,CAAC,GAAGI,IAA0C;MAE/EC,KAAK,CAACC,OAAO,GAAG,IAAIlB,WAAW,CAC7BJ,UAAU,CAACwB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAF,mBAAmB,CAACU,YAAY,GAAG;EACjCR,QAAQ,EAAEJ;AACZ,CAAC"}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","useContext","useRef","GlobalState","jsx","_jsx","context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","state","current","stateProxy","initialState","Provider","value","defaultProps"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\n\nimport { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n useContext,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nimport { type ValueOrInitializerT } from './utils';\n\nconst context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = useContext(context);\n /* eslint-enable react-hooks/rules-of-hooks */\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>,\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nexport default function GlobalStateProvider<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n) {\n const state = useRef<GlobalState<StateT, SsrContextT>>();\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return (\n <context.Provider value={state.current}>\n {children}\n </context.Provider>\n );\n}\n\nGlobalStateProvider.defaultProps = {\n children: undefined,\n};\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cA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B,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDR,UACF,CAAC;IACH;EACF;EACA,oBACEV,IAAA,CAACC,OAAO,CAACkB,QAAQ;IAACC,KAAK,EAAEL,KAAK,CAACC,OAAQ;IAAAH,QAAA,EACpCA;EAAQ,CACO,CAAC;AAEvB;AAEAF,mBAAmB,CAACU,YAAY,GAAG;EACjCR,QAAQ,EAAEJ;AACZ,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"SsrContext.js","names":["SsrContext","constructor","state","_defineProperty"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAOtCC,WAAWA,CAACC,KAAc,EAAE;IAAAC,eAAA,gBANX,KAAK;IAAAA,eAAA,kBAEK,EAAE;IAK3B,IAAI,CAACD,KAAK,GAAGA,KAAK;EACpB;AACF"}
1
+ {"version":3,"file":"SsrContext.js","names":["SsrContext","constructor","state","_defineProperty"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAOtCC,WAAWA,CAACC,KAAc,EAAE;IAAAC,eAAA,gBANX,KAAK;IAAAA,eAAA,kBAEK,EAAE;IAK3B,IAAI,CAACD,KAAK,GAAGA,KAAK;EACpB;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","useAsyncData","newAsyncDataEnvelope","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n} from './useAsyncCollection';\n\nimport useAsyncData, {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type {\n AsyncDataEnvelopeT,\n AsyncDataLoaderT,\n UseAsyncDataOptionsT,\n UseAsyncDataResT,\n} from './useAsyncData';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAIzB,OAAOC,YAAY,IAEjBC,oBAAoB;AAGtB,OAAOC,cAAc;AAerB,SACEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBM,oBAAoB,EACpBH,UAAU,EACVC,kBAAkB,EAClBC,YAAY,EACZE,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBM,oBAAoB;EACpBH,UAAU;EACVC,kBAAkB;EAClBC,YAAY;EACZE;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ"}
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","useAsyncData","newAsyncDataEnvelope","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n} from './useAsyncCollection';\n\nimport useAsyncData, {\n type UseAsyncDataI,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type {\n AsyncDataEnvelopeT,\n AsyncDataLoaderT,\n UseAsyncDataOptionsT,\n UseAsyncDataResT,\n} from './useAsyncData';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAIzB,OAAOC,YAAY,IAEjBC,oBAAoB;AAGtB,OAAOC,cAAc;AAerB,SACEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBM,oBAAoB,EACpBH,UAAU,EACVC,kBAAkB,EAClBC,YAAY,EACZE,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBM,oBAAoB;EACpBH,UAAU;EACVC,kBAAkB;EAClBC,YAAY;EACZE;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link 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 */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,YAAY;;AAWnB;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;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB"}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useAsyncData","useAsyncCollection","id","path","loader","options","arguments","length","undefined","itemPath","oldData"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses an item in an async collection.\n */\n\nimport useAsyncData, {\n type DataInEnvelopeAtPathT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n} from './useAsyncData';\n\nimport { type ForceT, type LockT, type TypeLock } from './utils';\n\nexport type AsyncCollectionLoaderT<DataT> =\n (id: string, oldData: null | DataT) => DataT | Promise<DataT>;\n\n/**\n * Resolves and stores at the given `path` of global state elements of\n * an asynchronous data collection. In other words, it is an auxiliar wrapper\n * around {@link useAsyncData}, which uses a loader which resolves to different\n * data, based on ID argument passed in, and stores data fetched for different\n * IDs in the state.\n * @param id ID of the collection item to load & use.\n * @param path The global state path where entire collection should be\n * stored.\n * @param loader A loader function, which takes an\n * ID of data to load, and resolves to the corresponding data.\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link 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 */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> =\n DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<DataT>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const itemPath = path ? `${path}.${id}` : id;\n return useAsyncData<ForceT, DataT>(\n itemPath,\n (oldData: null | DataT) => loader(id, oldData),\n options,\n );\n}\n\nexport default useAsyncCollection;\n\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n id: string,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,YAAY;;AAWnB;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;;AA0BA,SAASC,kBAAkBA,CACzBC,EAAU,EACVC,IAA+B,EAC/BC,MAAqC,EAEZ;EAAA,IADzBC,OAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAElC,MAAMG,QAAQ,GAAGN,IAAI,GAAI,GAAEA,IAAK,IAAGD,EAAG,EAAC,GAAGA,EAAE;EAC5C,OAAOF,YAAY,CACjBS,QAAQ,EACPC,OAAqB,IAAKN,MAAM,CAACF,EAAE,EAAEQ,OAAO,CAAC,EAC9CL,OACF,CAAC;AACH;AAEA,eAAeJ,kBAAkB","ignoreList":[]}
@@ -13,11 +13,15 @@ const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
13
13
 
14
14
  export function newAsyncDataEnvelope() {
15
15
  let initialData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
16
+ let {
17
+ numRefs = 0,
18
+ timestamp = 0
19
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
16
20
  return {
17
21
  data: initialData,
18
- numRefs: 0,
22
+ numRefs,
19
23
  operationId: '',
20
- timestamp: 0
24
+ timestamp
21
25
  };
22
26
  }
23
27
  /**
@@ -41,7 +45,6 @@ async function load(path, loader, globalState, oldData) {
41
45
  console.log(`ReactGlobalState: useAsyncData data (re-)loading. Path: "${path || ''}"`);
42
46
  /* eslint-enable no-console */
43
47
  }
44
-
45
48
  const operationId = opIdPrefix + uuid();
46
49
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
47
50
  globalState.set(operationIdPath, operationId);
@@ -54,7 +57,6 @@ async function load(path, loader, globalState, oldData) {
54
57
  console.log('Data:', cloneDeep(data));
55
58
  /* eslint-enable no-console */
56
59
  }
57
-
58
60
  globalState.set(path, {
59
61
  ...state,
60
62
  data,
@@ -156,7 +158,6 @@ function useAsyncData(path, loader) {
156
158
  console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
157
159
  /* eslint-enable no-console */
158
160
  }
159
-
160
161
  globalState.dropDependencies(path || '');
161
162
  globalState.set(path, {
162
163
  ...state2,
@@ -181,16 +182,20 @@ function useAsyncData(path, loader) {
181
182
  loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps
182
183
  }
183
184
  });
184
-
185
- const deps = options.deps || [];
186
185
  useEffect(() => {
187
186
  // eslint-disable-line react-hooks/rules-of-hooks
188
- if (globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
187
+ const {
188
+ deps
189
+ } = options;
190
+ if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {
189
191
  load(path, loader, globalState, null);
190
192
  }
191
- }, deps); // eslint-disable-line react-hooks/exhaustive-deps
192
- }
193
193
 
194
+ // Here we need to default to empty array, so that this hook is re-evaluated
195
+ // only when dependencies specified in options change, and it should not be
196
+ // re-evaluated at all if no `deps` option is used.
197
+ }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps
198
+ }
194
199
  const [localState] = useGlobalState(path, newAsyncDataEnvelope());
195
200
  return {
196
201
  data: maxage < Date.now() - localState.timestamp ? null : localState.data,
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","data","numRefs","operationId","timestamp","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","loading","Boolean","reload","customLoader"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs: 0,\n operationId: '',\n timestamp: 0,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n const deps = options.deps || [];\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\n }\n }, deps); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAEP;EAAA,IAD3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAEhC,OAAO;IACLG,IAAI,EAAEJ,WAAW;IACjBK,OAAO,EAAE,CAAC;IACVC,WAAW,EAAE,EAAE;IACfC,SAAS,EAAE;EACb,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AAC;AACH;AAEA,eAAeoB,YAAY"}
1
+ {"version":3,"file":"useAsyncData.js","names":["cloneDeep","useEffect","v4","uuid","MIN_MS","getGlobalState","useGlobalState","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","load","path","loader","globalState","oldData","opIdPrefix","process","env","NODE_ENV","console","log","operationIdPath","set","get","state","groupCollapsed","Date","now","groupEnd","useAsyncData","options","maxage","refreshAge","garbageCollectAge","initialValue","ssrContext","noSSR","pending","push","numRefsPath","state2","dropDependencies","loadTriggered","charAt","deps","hasChangedDependencies","localState","loading","Boolean","reload","customLoader"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { cloneDeep } from 'lodash';\nimport { useEffect } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n isDebugMode,\n} from './utils';\n\nimport GlobalState from './GlobalState';\nimport SsrContext from './SsrContext';\n\nconst DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\nexport type AsyncDataLoaderT<DataT>\n= (oldData: null | DataT) => DataT | Promise<DataT>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: (loader?: AsyncDataLoaderT<DataT>) => Promise<void>;\n timestamp: number;\n};\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nasync function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n oldData: DataT | null,\n opIdPrefix: 'C' | 'S' = 'C',\n): Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: useAsyncData data (re-)loading. Path: \"${path || ''}\"`,\n );\n /* eslint-enable no-console */\n }\n const operationId = opIdPrefix + uuid();\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n globalState.set<ForceT, string>(operationIdPath, operationId);\n const data = await loader(\n oldData || (globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path)).data,\n );\n const state: AsyncDataEnvelopeT<DataT> = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n if (operationId === state.operationId) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: useAsyncData data (re-)loaded. Path: \"${\n path || ''\n }\"`,\n );\n console.log('Data:', cloneDeep(data));\n /* eslint-enable no-console */\n }\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state. When multiple components rely on asynchronous data at the same `path`,\n * the data are resolved once, and reused until their age is within specified\n * bounds. Once the data are stale, the hook allows to refresh them. It also\n * garbage-collects stale data from the global state when the last component\n * relying on them is unmounted.\n * @param path Dot-delimitered state path, where data envelop is\n * stored.\n * @param loader Asynchronous function which resolves (loads)\n * data, which should be stored at the global state `path`. When multiple\n * components\n * use `useAsyncData()` hook for the same `path`, the library assumes that all\n * hook instances are called with the same `loader` (_i.e._ whichever of these\n * loaders is used to resolve async data, the result is acceptable to be reused\n * in all related components).\n * @param options Additional options.\n * @param options.deps An array of dependencies, which trigger\n * data reload when changed. Given dependency changes are watched shallowly\n * (similarly to the standard React's\n * [useEffect()](https://reactjs.org/docs/hooks-reference.html#useeffect)).\n * @param options.noSSR If `true`, this hook won't load data during\n * server-side rendering.\n * @param options.garbageCollectAge The maximum age of data\n * (in milliseconds), after which they are dropped from the state when the last\n * component referencing them via `useAsyncData()` hook unmounts. Defaults to\n * `maxage` option value.\n * @param options.maxage The maximum age of\n * data (in milliseconds) acceptable to the hook's caller. If loaded data are\n * older than this value, `null` is returned instead. Defaults to 5 minutes.\n * @param options.refreshAge The maximum age of data\n * (in milliseconds), after which their refreshment will be triggered when\n * any component referencing them via `useAsyncData()` hook (re-)renders.\n * Defaults to `maxage` value.\n * @return Returns an object with three fields: `data` holds the actual result of\n * last `loader` invokation, if any, and if satisfies `maxage` limit; `loading`\n * is a boolean flag, which is `true` if data are being loaded (the hook is\n * waiting for `loader` function resolution); `timestamp` (in milliseconds)\n * is Unix timestamp of related data currently loaded into the global state.\n *\n * Note that loaded data, if any, are stored at the given `path` of global state\n * along with related meta-information, using slightly different state segment\n * structure (see {@link AsyncDataEnvelopeT}). That segment of the global state\n * can be accessed, and even modified using other hooks,\n * _e.g._ {@link useGlobalState}, but doing so you may interfere with related\n * `useAsyncData()` hooks logic.\n */\n\nexport type DataInEnvelopeAtPathT<StateT, PathT extends null | string | undefined>\n= ValueAtPathT<StateT, PathT, never> extends AsyncDataEnvelopeT<unknown>\n ? Exclude<ValueAtPathT<StateT, PathT, never>['data'], null>\n : void;\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<StateT, PathT> =\n DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage === undefined\n ? DEFAULT_MAXAGE : options.maxage;\n\n const refreshAge: number = options.refreshAge === undefined\n ? maxage : options.refreshAge;\n\n const garbageCollectAge: number = options.garbageCollectAge === undefined\n ? maxage : options.garbageCollectAge;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n if (globalState.ssrContext && !options.noSSR) {\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(path, loader, globalState, state.data, 'S'),\n );\n }\n } else {\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n return () => {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n };\n }, [garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n let loadTriggered = false;\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n if (refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {\n load(path, loader, globalState, state2.data);\n loadTriggered = true; // eslint-disable-line react-hooks/exhaustive-deps\n }\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const { deps } = options;\n if (deps && globalState.hasChangedDependencies(path || '', deps) && !loadTriggered) {\n load(path, loader, globalState, null);\n }\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n\n reload: (customLoader?: AsyncDataLoaderT<DataT>) => load(\n path,\n customLoader || loader,\n globalState,\n null,\n ),\n\n timestamp: localState.timestamp,\n };\n}\n\nexport default useAsyncData;\n\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,WAAW;AAMb,MAAMC,cAAc,GAAG,CAAC,GAAGJ,MAAM,CAAC,CAAC;;AAYnC,OAAO,SAASK,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,GAAAJ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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,CAACvC;EACxB,CAAC;AACH;AAEA,eAAesB,YAAY","ignoreList":[]}
@@ -55,9 +55,14 @@ import { isDebugMode } from "./utils";
55
55
  *
56
56
  * Also, similar to the standard React's state setters, `setValue()` is
57
57
  * stable function: it does not change between component re-renders.
58
- */ // "Enforced type overload"
58
+ */
59
+
60
+ // "Enforced type overload"
61
+
59
62
  // "Entire state overload"
63
+
60
64
  // "State evaluation overload"
65
+
61
66
  function useGlobalState(path, initialValue) {
62
67
  const globalState = getGlobalState();
63
68
  const ref = useRef();
@@ -74,8 +79,18 @@ function useGlobalState(path, initialValue) {
74
79
  console.groupEnd();
75
80
  /* eslint-enable no-console */
76
81
  }
77
-
78
82
  rc.globalState.set(rc.path, newState);
83
+
84
+ // NOTE: The regular global state's update notifications, automatically
85
+ // triggered by the rc.globalState.set() call above, are batched, and
86
+ // scheduled to fire asynchronosuly at a later time, which is problematic
87
+ // for managed text inputs - if they have their value update delayed to
88
+ // future render cycles, it will result in reset of their cursor position
89
+ // to the value end. Calling the rc.emitter.emit() below causes a sooner
90
+ // state update for the current component, thus working around the issue.
91
+ // For additional details see the original issue:
92
+ // https://github.com/birdofpreyru/react-global-state/issues/22
93
+ if (newState !== rc.state) rc.emitter.emit();
79
94
  },
80
95
  state: isFunction(initialValue) ? initialValue() : initialValue,
81
96
  watcher: () => {