@dr.pogodin/react-global-state 0.19.1 → 0.19.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.
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _lodash = require("lodash");
8
+ var _utils = require("./utils");
9
+ const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
10
+ class GlobalState {
11
+ #asyncDataAbortCallbacks = {};
12
+ #dependencies = {};
13
+ #initialState;
14
+
15
+ // TODO: It is tempting to replace watchers here by
16
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
17
+ // current watchers for emitting later, and this is not something
18
+ // Emitter supports right now.
19
+ #watchers = [];
20
+ #nextNotifierId;
21
+ #currentState;
22
+
23
+ /**
24
+ * Creates a new global state object.
25
+ * @param initialState Intial global state content.
26
+ * @param ssrContext Server-side rendering context.
27
+ */
28
+ constructor(initialState, ssrContext) {
29
+ this.#currentState = initialState;
30
+ this.#initialState = initialState;
31
+ if (ssrContext) {
32
+ /* eslint-disable no-param-reassign */
33
+ ssrContext.dirty = false;
34
+ ssrContext.pending = [];
35
+ ssrContext.state = this.#currentState;
36
+ /* eslint-enable no-param-reassign */
37
+
38
+ this.ssrContext = ssrContext;
39
+ }
40
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
41
+ /* eslint-disable no-console */
42
+ let msg = 'New ReactGlobalState created';
43
+ if (ssrContext) msg += ' (SSR mode)';
44
+ console.groupCollapsed(msg);
45
+ console.log('Initial state:', (0, _utils.cloneDeepForLog)(initialState));
46
+ console.groupEnd();
47
+ /* eslint-enable no-console */
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Returns the number of currently registered async data abort callbacks,
53
+ * just for the sake of testing the library.
54
+ */
55
+ get numAsyncDataAbortCallbacks() {
56
+ return Object.keys(this.#asyncDataAbortCallbacks).length;
57
+ }
58
+
59
+ /**
60
+ * If `aborted` is "true" and there is an abort callback registered for
61
+ * the specified operation, it triggers the callback. Then, in any case,
62
+ * it drops the callback.
63
+ */
64
+ asyncDataLoadDone(opid, aborted) {
65
+ if (aborted) this.#asyncDataAbortCallbacks[opid]?.();
66
+ delete this.#asyncDataAbortCallbacks[opid];
67
+ }
68
+
69
+ /**
70
+ * Drops the record of dependencies, if any, for the given path.
71
+ */
72
+ dropDependencies(path) {
73
+ delete this.#dependencies[path];
74
+ }
75
+
76
+ /**
77
+ * Checks if given `deps` are different from previously recorded ones for
78
+ * the given `path`. If they are, `deps` are recorded as the new deps for
79
+ * the `path`, and also the array is frozen, to prevent it from being
80
+ * modified.
81
+ *
82
+ * TODO: This may not work as expected if path string is not normalized,
83
+ * and the for the same path different alternative ways to spell it down
84
+ * are used. We should normalize given path here, I guess, or on a higher
85
+ * level in the logic?
86
+ */
87
+ hasChangedDependencies(path, deps) {
88
+ const prevDeps = this.#dependencies[path];
89
+ let changed = !prevDeps || prevDeps.length !== deps.length;
90
+ for (let i = 0; !changed && i < deps.length; ++i) {
91
+ changed = prevDeps[i] !== deps[i];
92
+ }
93
+ this.#dependencies[path] = Object.freeze(deps);
94
+ return changed;
95
+ }
96
+
97
+ /**
98
+ * Gets entire state, the same way as .get(null, opts) would do.
99
+ * @param opts.initialState
100
+ * @param opts.initialValue
101
+ */
102
+ getEntireState(opts) {
103
+ let state = opts?.initialState ? this.#initialState : this.#currentState;
104
+ if (state !== undefined || opts?.initialValue === undefined) return state;
105
+ const iv = opts.initialValue;
106
+ state = (0, _lodash.isFunction)(iv) ? iv() : iv;
107
+ if (this.#currentState === undefined) this.setEntireState(state);
108
+ return state;
109
+ }
110
+
111
+ /**
112
+ * Notifies all connected state watchers that a state update has happened.
113
+ */
114
+ notifyStateUpdate(path, value) {
115
+ if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
116
+ /* eslint-disable no-console */
117
+ const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
118
+ console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
119
+ console.log('New value:', (0, _utils.cloneDeepForLog)(value, path ?? ''));
120
+ console.log('New state:', (0, _utils.cloneDeepForLog)(this.#currentState));
121
+ console.groupEnd();
122
+ /* eslint-enable no-console */
123
+ }
124
+ if (this.ssrContext) {
125
+ this.ssrContext.dirty = true;
126
+ this.ssrContext.state = this.#currentState;
127
+ } else if (!this.#nextNotifierId) {
128
+ this.#nextNotifierId = setTimeout(() => {
129
+ this.#nextNotifierId = undefined;
130
+ const watchers = [...this.#watchers];
131
+ for (const watcher of watchers) watcher();
132
+ });
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Registers an abort callback for an async data retrieval operation with
138
+ * the given operation ID. Throws if already registered.
139
+ */
140
+ setAsyncDataAbortCallback(opid, cb) {
141
+ this.#asyncDataAbortCallbacks[opid] = cb;
142
+ }
143
+
144
+ /**
145
+ * Sets entire state, the same way as .set(null, value) would do.
146
+ * @param value
147
+ */
148
+ setEntireState(value) {
149
+ if (this.#currentState !== value) {
150
+ this.#currentState = value;
151
+ this.notifyStateUpdate(null, value);
152
+ }
153
+ return value;
154
+ }
155
+
156
+ /**
157
+ * Gets current or initial value at the specified "path" of the global state.
158
+ * @param path Dot-delimitered state path.
159
+ * @param options Additional options.
160
+ * @param options.initialState If "true" the value will be read
161
+ * from the initial state instead of the current one.
162
+ * @param options.initialValue If the value read from the "path" is
163
+ * "undefined", this "initialValue" will be returned instead. In such case
164
+ * "initialValue" will also be written to the "path" of the current global
165
+ * state (no matter "initialState" flag), if "undefined" is stored there.
166
+ * @return Retrieved value.
167
+ */
168
+
169
+ // .get() without arguments just falls back to .getEntireState().
170
+
171
+ // This variant attempts to automatically resolve and check the type of value
172
+ // at the given path, as precise as the actual state and path types permit.
173
+ // If the automatic path resolution is not possible, the ValueT fallsback
174
+ // to `never` (or to `undefined` in some cases), effectively forbidding
175
+ // to use this .get() variant.
176
+
177
+ // This variant is not callable by default (without generic arguments),
178
+ // otherwise it allows to set the correct ValueT directly.
179
+
180
+ get(path, opts) {
181
+ if ((0, _lodash.isNil)(path)) {
182
+ const res = this.getEntireState(opts);
183
+ return res;
184
+ }
185
+ const state = opts?.initialState ? this.#initialState : this.#currentState;
186
+ let res = (0, _lodash.get)(state, path);
187
+ if (res !== undefined || opts?.initialValue === undefined) return res;
188
+ const iv = opts.initialValue;
189
+ res = (0, _lodash.isFunction)(iv) ? iv() : iv;
190
+
191
+ // TODO: Revise.
192
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
193
+ if (!opts.initialState || this.get(path) === undefined) {
194
+ this.set(path, res);
195
+ }
196
+ return res;
197
+ }
198
+
199
+ /**
200
+ * Writes the `value` to given global state `path`.
201
+ * @param path Dot-delimitered state path. If not given, entire
202
+ * global state content is replaced by the `value`.
203
+ * @param value The value.
204
+ * @return Given `value` itself.
205
+ */
206
+
207
+ // This variant attempts automatic value type resolution & checking.
208
+
209
+ // This variant is disabled by default, otherwise allows to give
210
+ // expected value type explicitly.
211
+
212
+ set(path, value) {
213
+ if ((0, _lodash.isNil)(path)) return this.setEntireState(value);
214
+
215
+ // TODO: Revise.
216
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
217
+ if (value !== this.get(path)) {
218
+ const root = {
219
+ state: this.#currentState
220
+ };
221
+ let segIdx = 0;
222
+
223
+ // TODO: It is not 100% correct, as `pos` can be an array, or any other
224
+ // value as we travel through the state tree. To simplify the typing for
225
+ // now, I guess, we can go with this record type, though.
226
+ let pos = root;
227
+ const pathSegments = (0, _lodash.toPath)(`state.${path}`);
228
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
229
+ const seg = pathSegments[segIdx];
230
+
231
+ // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.
232
+ const next = pos[seg];
233
+ if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
234
+ ...next
235
+ };else {
236
+ // We arrived to a state sub-segment, where the remaining part of
237
+ // the update path does not exist yet. We rely on lodash's set()
238
+ // function to create the remaining path, and set the value.
239
+ (0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
240
+ break;
241
+ }
242
+ pos = pos[seg];
243
+ }
244
+ if (segIdx === pathSegments.length - 1) {
245
+ pos[pathSegments[segIdx]] = value;
246
+ }
247
+ this.#currentState = root.state;
248
+ this.notifyStateUpdate(path, value);
249
+ }
250
+ return value;
251
+ }
252
+
253
+ /**
254
+ * Unsubscribes `callback` from watching state updates; no operation if
255
+ * `callback` is not subscribed to the state updates.
256
+ * @param callback
257
+ * @throws if {@link SsrContext} is attached to the state instance: the state
258
+ * watching functionality is intended for client-side (non-SSR) only.
259
+ */
260
+ unWatch(callback) {
261
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
262
+ const watchers = this.#watchers;
263
+ const pos = watchers.indexOf(callback);
264
+ if (pos >= 0) {
265
+ watchers[pos] = watchers[watchers.length - 1];
266
+ watchers.pop();
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Subscribes `callback` to watch state updates; no operation if
272
+ * `callback` is already subscribed to this state instance.
273
+ * @param callback It will be called without any arguments every
274
+ * time the state content changes (note, howhever, separate state updates can
275
+ * be applied to the state at once, and watching callbacks will be called once
276
+ * after such bulk update).
277
+ * @throws if {@link SsrContext} is attached to the state instance: the state
278
+ * watching functionality is intended for client-side (non-SSR) only.
279
+ */
280
+ watch(callback) {
281
+ if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
282
+ const watchers = this.#watchers;
283
+ if (!watchers.includes(callback)) {
284
+ watchers.push(callback);
285
+ }
286
+ }
287
+ }
288
+ exports.default = GlobalState;
289
+ //# sourceMappingURL=GlobalState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalState.js","names":["_lodash","require","_utils","ERR_NO_SSR_WATCH","GlobalState","asyncDataAbortCallbacks","dependencies","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeepForLog","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","freeze","getEntireState","opts","undefined","initialValue","iv","isFunction","setEntireState","notifyStateUpdate","value","p","setTimeout","watcher","setAsyncDataAbortCallback","cb","get","isNil","res","set","root","segIdx","pos","pathSegments","toPath","seg","next","Array","isArray","isObject","slice","unWatch","callback","Error","indexOf","pop","watch","includes","push","exports","default"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks: Record<string, () => void> = {};\n\n #dependencies: Record<string, readonly unknown[]> = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return Object.keys(this.#asyncDataAbortCallbacks).length;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks[opid]?.();\n delete this.#asyncDataAbortCallbacks[opid];\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\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 * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = isFunction(iv) ? iv() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks[opid] = cb;\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) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === 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 // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\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] as Record<string, unknown>;\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): void {\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): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;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/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ exports.getGlobalState = getGlobalState;
9
+ exports.getSsrContext = getSsrContext;
10
+ var _lodash = require("lodash");
11
+ var _react = require("react");
12
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
13
+ var _jsxRuntime = require("react/jsx-runtime");
14
+ const Context = /*#__PURE__*/(0, _react.createContext)(null);
15
+
16
+ /**
17
+ * Gets {@link GlobalState} instance from the context. In most cases
18
+ * you should use {@link useGlobalState}, and other hooks to interact with
19
+ * the global state, instead of accessing it directly.
20
+ * @return
21
+ */
22
+ function getGlobalState() {
23
+ // TODO: Think about it: on one hand we on purpose called this function
24
+ // as getGlobalState(), so that ppl looking for the state hook prefer using
25
+ // useGlobalState(), while this getGlobalState() is reserved for nieche cases;
26
+ // on the other hand, perhaps we can rename it into useSomething, to both
27
+ // follow conventions, and to keep stuff clearly named at the same time.
28
+ // eslint-disable-next-line react-hooks/rules-of-hooks
29
+ const globalState = (0, _react.use)(Context);
30
+ if (!globalState) throw new Error('Missing GlobalStateProvider');
31
+ return globalState;
32
+ }
33
+
34
+ /**
35
+ * @category Hooks
36
+ * @desc Gets SSR context.
37
+ * @param throwWithoutSsrContext If `true` (default),
38
+ * this hook will throw if no SSR context is attached to the global state;
39
+ * set `false` to not throw in such case. In either case the hook will throw
40
+ * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
41
+ * @returns SSR context.
42
+ * @throws
43
+ * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
44
+ * in the rendered React tree.
45
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
46
+ * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
47
+ */
48
+ function getSsrContext(throwWithoutSsrContext = true) {
49
+ const {
50
+ ssrContext
51
+ } = getGlobalState();
52
+ if (!ssrContext && throwWithoutSsrContext) {
53
+ throw new Error('No SSR context found');
54
+ }
55
+ return ssrContext;
56
+ }
57
+ /**
58
+ * Provides global state to its children.
59
+ * @param prop.children Component children, which will be provided with
60
+ * the global state, and rendered in place of the provider.
61
+ * @param prop.initialState Initial content of the global state.
62
+ * @param prop.ssrContext Server-side rendering (SSR) context.
63
+ * @param prop.stateProxy This option is useful for code
64
+ * splitting and SSR implementation:
65
+ * - If `true`, this provider instance will fetch and reuse the global state
66
+ * from a parent provider.
67
+ * - If `GlobalState` instance, it will be used by this provider.
68
+ * - If not given, a new `GlobalState` instance will be created and used.
69
+ */
70
+ const GlobalStateProvider = ({
71
+ children,
72
+ ...rest
73
+ }) => {
74
+ const localStateRef = (0, _react.useRef)(undefined);
75
+ let state;
76
+ // TODO: Revise.
77
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
78
+ if ('stateProxy' in rest && rest.stateProxy) {
79
+ localStateRef.current = undefined;
80
+ state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
81
+ } else {
82
+ if (!localStateRef.current) {
83
+ const {
84
+ initialState,
85
+ ssrContext
86
+ } = rest;
87
+ localStateRef.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
88
+ }
89
+ state = localStateRef.current;
90
+ }
91
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(Context, {
92
+ value: state,
93
+ children: children
94
+ });
95
+ };
96
+ var _default = exports.default = GlobalStateProvider;
97
+ //# sourceMappingURL=GlobalStateProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","Context","createContext","getGlobalState","globalState","use","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localStateRef","useRef","undefined","state","stateProxy","current","initialState","GlobalState","isFunction","jsx","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type 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 // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n const localStateRef = useRef<GST>(undefined);\n let state: GST;\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ('stateProxy' in rest && rest.stateProxy) {\n localStateRef.current = undefined;\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else {\n if (!localStateRef.current) {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n localStateRef.current = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n state = localStateRef.current;\n }\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,UAA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K,EAAEP,KAAM;IAAAL,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAAC,IAAAa,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEahB,mBAAmB","ignoreList":[]}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ class SsrContext {
8
+ dirty = false;
9
+ pending = [];
10
+ constructor(state) {
11
+ this.state = state;
12
+ }
13
+ }
14
+ exports.default = SsrContext;
15
+ //# sourceMappingURL=SsrContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SsrContext.js","names":["SsrContext","dirty","pending","constructor","state","exports","default"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Array<Promise<void>> = [];\n\n constructor(public state?: StateT) { }\n}\n"],"mappings":";;;;;;AAAe,MAAMA,UAAU,CAAS;EACtCC,KAAK,GAAY,KAAK;EAEtBC,OAAO,GAAyB,EAAE;EAElCC,WAAWA,CAAQC,KAAc,EAAE;IAAA,KAAhBA,KAAc,GAAdA,KAAc;EAAI;AACvC;AAACC,OAAA,CAAAC,OAAA,GAAAN,UAAA","ignoreList":[]}
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ Object.defineProperty(exports, "GlobalState", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _GlobalState.default;
11
+ }
12
+ });
13
+ Object.defineProperty(exports, "GlobalStateProvider", {
14
+ enumerable: true,
15
+ get: function () {
16
+ return _GlobalStateProvider.default;
17
+ }
18
+ });
19
+ Object.defineProperty(exports, "SsrContext", {
20
+ enumerable: true,
21
+ get: function () {
22
+ return _SsrContext.default;
23
+ }
24
+ });
25
+ Object.defineProperty(exports, "getGlobalState", {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _GlobalStateProvider.getGlobalState;
29
+ }
30
+ });
31
+ Object.defineProperty(exports, "getSsrContext", {
32
+ enumerable: true,
33
+ get: function () {
34
+ return _GlobalStateProvider.getSsrContext;
35
+ }
36
+ });
37
+ Object.defineProperty(exports, "newAsyncDataEnvelope", {
38
+ enumerable: true,
39
+ get: function () {
40
+ return _useAsyncData.newAsyncDataEnvelope;
41
+ }
42
+ });
43
+ Object.defineProperty(exports, "useAsyncCollection", {
44
+ enumerable: true,
45
+ get: function () {
46
+ return _useAsyncCollection.default;
47
+ }
48
+ });
49
+ Object.defineProperty(exports, "useAsyncData", {
50
+ enumerable: true,
51
+ get: function () {
52
+ return _useAsyncData.useAsyncData;
53
+ }
54
+ });
55
+ Object.defineProperty(exports, "useGlobalState", {
56
+ enumerable: true,
57
+ get: function () {
58
+ return _useGlobalState.default;
59
+ }
60
+ });
61
+ exports.withGlobalStateType = withGlobalStateType;
62
+ var _GlobalState = _interopRequireDefault(require("./GlobalState"));
63
+ var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
64
+ var _SsrContext = _interopRequireDefault(require("./SsrContext"));
65
+ var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
66
+ var _useAsyncData = require("./useAsyncData");
67
+ var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
68
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
69
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
70
+
71
+ const api = {
72
+ // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?
73
+ // Perhaps, we should tune something in its config settings, as it seems to mix
74
+ // some extra sorting logic, which I am not sure I like.
75
+ GlobalState: _GlobalState.default,
76
+ GlobalStateProvider: _GlobalStateProvider.default,
77
+ SsrContext: _SsrContext.default,
78
+ getGlobalState: _GlobalStateProvider.getGlobalState,
79
+ getSsrContext: _GlobalStateProvider.getSsrContext,
80
+ newAsyncDataEnvelope: _useAsyncData.newAsyncDataEnvelope,
81
+ useAsyncCollection: _useAsyncCollection.default,
82
+ useAsyncData: _useAsyncData.useAsyncData,
83
+ useGlobalState: _useGlobalState.default
84
+ };
85
+ function withGlobalStateType() {
86
+ return api;
87
+ }
88
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","api","GlobalState","GlobalStateProvider","SsrContext","getGlobalState","getSsrContext","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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 // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAA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