@dr.pogodin/react-global-state 0.23.0 → 0.25.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.
- package/LICENSE.md +1 -1
- package/build/{code → logic}/GlobalState.js +43 -52
- package/build/logic/GlobalState.js.map +1 -0
- package/build/logic/GlobalStateProvider.js +102 -0
- package/build/logic/GlobalStateProvider.js.map +1 -0
- package/build/logic/SsrContext.js +8 -0
- package/build/logic/SsrContext.js.map +1 -0
- package/build/{code → logic}/index.js +5 -5
- package/build/logic/index.js.map +1 -0
- package/build/{code → logic}/useAsyncCollection.js +88 -83
- package/build/logic/useAsyncCollection.js.map +1 -0
- package/build/{code → logic}/useAsyncData.js +175 -79
- package/build/logic/useAsyncData.js.map +1 -0
- package/build/{code → logic}/useGlobalState.js +8 -10
- package/build/logic/useGlobalState.js.map +1 -0
- package/build/{code → logic}/utils.js +8 -19
- package/build/logic/utils.js.map +1 -0
- package/build/types/GlobalStateProvider.d.ts +14 -16
- package/build/types/index.d.ts +4 -4
- package/build/types/utils.d.ts +2 -14
- package/package.json +29 -26
- package/build/code/GlobalState.js.map +0 -1
- package/build/code/GlobalStateProvider.js +0 -90
- package/build/code/GlobalStateProvider.js.map +0 -1
- package/build/code/SsrContext.js +0 -9
- package/build/code/SsrContext.js.map +0 -1
- package/build/code/index.js.map +0 -1
- package/build/code/useAsyncCollection.js.map +0 -1
- package/build/code/useAsyncData.js.map +0 -1
- package/build/code/useGlobalState.js.map +0 -1
- package/build/code/utils.js.map +0 -1
- package/eslint.config.mjs +0 -19
- package/tsconfig.json +0 -21
- package/tsconfig.types.json +0 -14
- package/tstyche.json +0 -6
package/LICENSE.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# MIT License
|
|
2
2
|
|
|
3
|
-
_Copyright © 2019–
|
|
3
|
+
_Copyright © 2019–2026, Dr. Sergey Pogodin_
|
|
4
4
|
— <doc@pogodin.studio> (https://dr.pogodin.studio)
|
|
5
5
|
|
|
6
6
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
@@ -1,41 +1,33 @@
|
|
|
1
|
-
function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
|
|
2
|
-
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) 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"); }
|
|
6
1
|
import { get, set, toPath } from 'lodash-es';
|
|
7
2
|
import { cloneDeepForLog, isDebugMode } from "./utils.js";
|
|
8
3
|
const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
|
|
9
|
-
var _asyncDataAbortCallbacks = /*#__PURE__*/new WeakMap();
|
|
10
|
-
var _dependencies = /*#__PURE__*/new WeakMap();
|
|
11
|
-
var _initialState = /*#__PURE__*/new WeakMap();
|
|
12
|
-
var _watchers = /*#__PURE__*/new WeakMap();
|
|
13
|
-
var _nextNotifierId = /*#__PURE__*/new WeakMap();
|
|
14
|
-
var _currentState = /*#__PURE__*/new WeakMap();
|
|
15
4
|
export default class GlobalState {
|
|
5
|
+
ssrContext;
|
|
6
|
+
#asyncDataAbortCallbacks = new Map();
|
|
7
|
+
#dependencies = new Map();
|
|
8
|
+
#initialState;
|
|
9
|
+
|
|
10
|
+
// TODO: It is tempting to replace watchers here by
|
|
11
|
+
// Emitter from @dr.pogodin/js-utils, but we need to clone
|
|
12
|
+
// current watchers for emitting later, and this is not something
|
|
13
|
+
// Emitter supports right now.
|
|
14
|
+
#watchers = [];
|
|
15
|
+
#nextNotifierId;
|
|
16
|
+
#currentState;
|
|
17
|
+
|
|
16
18
|
/**
|
|
17
19
|
* Creates a new global state object.
|
|
18
20
|
* @param initialState Intial global state content.
|
|
19
21
|
* @param ssrContext Server-side rendering context.
|
|
20
22
|
*/
|
|
21
23
|
constructor(initialState, ssrContext) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
_classPrivateFieldInitSpec(this, _initialState, void 0);
|
|
25
|
-
// TODO: It is tempting to replace watchers here by
|
|
26
|
-
// Emitter from @dr.pogodin/js-utils, but we need to clone
|
|
27
|
-
// current watchers for emitting later, and this is not something
|
|
28
|
-
// Emitter supports right now.
|
|
29
|
-
_classPrivateFieldInitSpec(this, _watchers, []);
|
|
30
|
-
_classPrivateFieldInitSpec(this, _nextNotifierId, void 0);
|
|
31
|
-
_classPrivateFieldInitSpec(this, _currentState, void 0);
|
|
32
|
-
_classPrivateFieldSet(_currentState, this, initialState);
|
|
33
|
-
_classPrivateFieldSet(_initialState, this, initialState);
|
|
24
|
+
this.#currentState = initialState;
|
|
25
|
+
this.#initialState = initialState;
|
|
34
26
|
if (ssrContext) {
|
|
35
27
|
/* eslint-disable no-param-reassign */
|
|
36
28
|
ssrContext.dirty = false;
|
|
37
29
|
ssrContext.pending = [];
|
|
38
|
-
ssrContext.state =
|
|
30
|
+
ssrContext.state = this.#currentState;
|
|
39
31
|
/* eslint-enable no-param-reassign */
|
|
40
32
|
|
|
41
33
|
this.ssrContext = ssrContext;
|
|
@@ -56,7 +48,7 @@ export default class GlobalState {
|
|
|
56
48
|
* just for the sake of testing the library.
|
|
57
49
|
*/
|
|
58
50
|
get numAsyncDataAbortCallbacks() {
|
|
59
|
-
return
|
|
51
|
+
return this.#asyncDataAbortCallbacks.size;
|
|
60
52
|
}
|
|
61
53
|
|
|
62
54
|
/**
|
|
@@ -65,16 +57,15 @@ export default class GlobalState {
|
|
|
65
57
|
* it drops the callback.
|
|
66
58
|
*/
|
|
67
59
|
asyncDataLoadDone(opid, aborted) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
_classPrivateFieldGet(_asyncDataAbortCallbacks, this).delete(opid);
|
|
60
|
+
if (aborted) this.#asyncDataAbortCallbacks.get(opid)?.();
|
|
61
|
+
this.#asyncDataAbortCallbacks.delete(opid);
|
|
71
62
|
}
|
|
72
63
|
|
|
73
64
|
/**
|
|
74
65
|
* Drops the record of dependencies, if any, for the given path.
|
|
75
66
|
*/
|
|
76
67
|
dropDependencies(path) {
|
|
77
|
-
|
|
68
|
+
this.#dependencies.delete(path);
|
|
78
69
|
}
|
|
79
70
|
|
|
80
71
|
/**
|
|
@@ -89,12 +80,12 @@ export default class GlobalState {
|
|
|
89
80
|
* level in the logic?
|
|
90
81
|
*/
|
|
91
82
|
hasChangedDependencies(path, deps) {
|
|
92
|
-
const prevDeps =
|
|
93
|
-
let changed =
|
|
83
|
+
const prevDeps = this.#dependencies.get(path);
|
|
84
|
+
let changed = prevDeps?.length !== deps.length;
|
|
94
85
|
for (let i = 0; !changed && i < deps.length; ++i) {
|
|
95
86
|
changed = prevDeps[i] !== deps[i];
|
|
96
87
|
}
|
|
97
|
-
|
|
88
|
+
this.#dependencies.set(path, Object.freeze(deps));
|
|
98
89
|
return changed;
|
|
99
90
|
}
|
|
100
91
|
|
|
@@ -104,11 +95,11 @@ export default class GlobalState {
|
|
|
104
95
|
* @param opts.initialValue
|
|
105
96
|
*/
|
|
106
97
|
getEntireState(opts) {
|
|
107
|
-
let state = opts
|
|
108
|
-
if (state !== undefined ||
|
|
98
|
+
let state = opts?.initialState ? this.#initialState : this.#currentState;
|
|
99
|
+
if (state !== undefined || opts?.initialValue === undefined) return state;
|
|
109
100
|
const iv = opts.initialValue;
|
|
110
101
|
state = typeof iv === 'function' ? iv() : iv;
|
|
111
|
-
if (
|
|
102
|
+
if (this.#currentState === undefined) this.setEntireState(state);
|
|
112
103
|
return state;
|
|
113
104
|
}
|
|
114
105
|
|
|
@@ -120,20 +111,20 @@ export default class GlobalState {
|
|
|
120
111
|
/* eslint-disable no-console */
|
|
121
112
|
const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
|
|
122
113
|
console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
|
|
123
|
-
console.log('New value:', cloneDeepForLog(value, path
|
|
124
|
-
console.log('New state:', cloneDeepForLog(
|
|
114
|
+
console.log('New value:', cloneDeepForLog(value, path ?? ''));
|
|
115
|
+
console.log('New state:', cloneDeepForLog(this.#currentState));
|
|
125
116
|
console.groupEnd();
|
|
126
117
|
/* eslint-enable no-console */
|
|
127
118
|
}
|
|
128
119
|
if (this.ssrContext) {
|
|
129
120
|
this.ssrContext.dirty = true;
|
|
130
|
-
this.ssrContext.state =
|
|
131
|
-
} else if (!
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
const watchers = [...
|
|
121
|
+
this.ssrContext.state = this.#currentState;
|
|
122
|
+
} else if (!this.#nextNotifierId) {
|
|
123
|
+
this.#nextNotifierId = setTimeout(() => {
|
|
124
|
+
this.#nextNotifierId = undefined;
|
|
125
|
+
const watchers = [...this.#watchers];
|
|
135
126
|
for (const watcher of watchers) watcher();
|
|
136
|
-
})
|
|
127
|
+
});
|
|
137
128
|
}
|
|
138
129
|
}
|
|
139
130
|
|
|
@@ -142,7 +133,7 @@ export default class GlobalState {
|
|
|
142
133
|
* the given operation ID. Throws if already registered.
|
|
143
134
|
*/
|
|
144
135
|
setAsyncDataAbortCallback(opid, cb) {
|
|
145
|
-
|
|
136
|
+
this.#asyncDataAbortCallbacks.set(opid, cb);
|
|
146
137
|
}
|
|
147
138
|
|
|
148
139
|
/**
|
|
@@ -150,8 +141,8 @@ export default class GlobalState {
|
|
|
150
141
|
* @param value
|
|
151
142
|
*/
|
|
152
143
|
setEntireState(value) {
|
|
153
|
-
if (
|
|
154
|
-
|
|
144
|
+
if (this.#currentState !== value) {
|
|
145
|
+
this.#currentState = value;
|
|
155
146
|
this.notifyStateUpdate(null, value);
|
|
156
147
|
}
|
|
157
148
|
return value;
|
|
@@ -186,9 +177,9 @@ export default class GlobalState {
|
|
|
186
177
|
const res = this.getEntireState(opts);
|
|
187
178
|
return res;
|
|
188
179
|
}
|
|
189
|
-
const state = opts
|
|
180
|
+
const state = opts?.initialState ? this.#initialState : this.#currentState;
|
|
190
181
|
let res = get(state, path);
|
|
191
|
-
if (res !== undefined ||
|
|
182
|
+
if (res !== undefined || opts?.initialValue === undefined) return res;
|
|
192
183
|
const iv = opts.initialValue;
|
|
193
184
|
res = typeof iv === 'function' ? iv() : iv;
|
|
194
185
|
|
|
@@ -220,7 +211,7 @@ export default class GlobalState {
|
|
|
220
211
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
221
212
|
if (value !== this.get(path)) {
|
|
222
213
|
const root = {
|
|
223
|
-
state:
|
|
214
|
+
state: this.#currentState
|
|
224
215
|
};
|
|
225
216
|
let segIdx = 0;
|
|
226
217
|
|
|
@@ -248,7 +239,7 @@ export default class GlobalState {
|
|
|
248
239
|
if (segIdx === pathSegments.length - 1) {
|
|
249
240
|
pos[pathSegments[segIdx]] = value;
|
|
250
241
|
}
|
|
251
|
-
|
|
242
|
+
this.#currentState = root.state;
|
|
252
243
|
this.notifyStateUpdate(path, value);
|
|
253
244
|
}
|
|
254
245
|
return value;
|
|
@@ -263,7 +254,7 @@ export default class GlobalState {
|
|
|
263
254
|
*/
|
|
264
255
|
unWatch(callback) {
|
|
265
256
|
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
266
|
-
const watchers =
|
|
257
|
+
const watchers = this.#watchers;
|
|
267
258
|
const pos = watchers.indexOf(callback);
|
|
268
259
|
if (pos >= 0) {
|
|
269
260
|
watchers[pos] = watchers[watchers.length - 1];
|
|
@@ -283,7 +274,7 @@ export default class GlobalState {
|
|
|
283
274
|
*/
|
|
284
275
|
watch(callback) {
|
|
285
276
|
if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
|
|
286
|
-
const watchers =
|
|
277
|
+
const watchers = this.#watchers;
|
|
287
278
|
if (!watchers.includes(callback)) {
|
|
288
279
|
watchers.push(callback);
|
|
289
280
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GlobalState.js","names":[],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\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 = new Map<string, () => void>();\n\n #dependencies = new Map<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 this.#asyncDataAbortCallbacks.size;\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.get(opid)?.();\n this.#asyncDataAbortCallbacks.delete(opid);\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n this.#dependencies.delete(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.get(path);\n let changed = prevDeps?.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies.set(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 = typeof iv === 'function' ? (iv as () => StateT)() : 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.set(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 (typeof path !== 'string') {\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 = typeof iv === 'function' ? (iv as () => ValueT)() : 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 (typeof path !== 'string') 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 (typeof next === 'object') 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":"AAAA,SAAS,GAAG,EAAE,GAAG,EAAE,MAAM,QAAQ,WAAW;AAAC,SAW3C,eAAe,EACf,WAAW;AAGb,MAAM,gBAAgB,GAAG,gDAAgD;AAOzE,eAAe,MAAM,WAAW,CAG9B;EACS,UAAU;EAEnB,CAAC,uBAAuB,GAAG,IAAI,GAAG,CAAqB,CAAC;EAExD,CAAC,YAAY,GAAG,IAAI,GAAG,CAA6B,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ACZ,QAAQ,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAE;MAC9C,QAAQ,CAAC,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,KAAK,CAAC,QAAmB,EAAQ;IAC/B,IAAI,IAAI,CAAC,UAAU,EAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC;IAEtD,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,QAAQ;IAC/B,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;MAChC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { c as _c } from "react/compiler-runtime";
|
|
2
|
+
import { createContext, use, useState } from 'react';
|
|
3
|
+
import GlobalState from "./GlobalState.js";
|
|
4
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
5
|
+
const Context = /*#__PURE__*/createContext(null);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Returns the GlobalState object from the context. In most cases you should use
|
|
9
|
+
* other hooks, like useGlobalState(), etc. to interact with the global state,
|
|
10
|
+
* instead of accessing the GlobalState object directly.
|
|
11
|
+
*/
|
|
12
|
+
export function useGlobalStateObject() {
|
|
13
|
+
const globalState = use(Context);
|
|
14
|
+
if (!globalState) throw new Error('Missing GlobalStateProvider');
|
|
15
|
+
return globalState;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Returns SSR context.
|
|
20
|
+
* @param throwWithoutSsrContext - If _true_ (default), this hook will throw
|
|
21
|
+
* if no SSR context is attached to the global state; set _false_ to not throw
|
|
22
|
+
* in such case. In either case this hook will throw if the <GlobalStateProvider>
|
|
23
|
+
* (hence the global state) is missing.
|
|
24
|
+
* @returns SSR context.
|
|
25
|
+
* @throws
|
|
26
|
+
* - If current component has no parent <GlobalStateProvider> in the rendered
|
|
27
|
+
* React tree.
|
|
28
|
+
* - If `throwWithoutSsrContext` is _true_ (default), and there is no SSR
|
|
29
|
+
* context attached to the global state provided by <GlobalStateProvider>.
|
|
30
|
+
*/
|
|
31
|
+
export function useSsrContext(t0) {
|
|
32
|
+
const throwWithoutSsrContext = t0 === undefined ? true : t0;
|
|
33
|
+
const {
|
|
34
|
+
ssrContext
|
|
35
|
+
} = useGlobalStateObject();
|
|
36
|
+
if (!ssrContext && throwWithoutSsrContext) {
|
|
37
|
+
throw new Error("No SSR context found");
|
|
38
|
+
}
|
|
39
|
+
return ssrContext;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Provides global state to its children.
|
|
43
|
+
* @param prop.children Component children, which will be provided with
|
|
44
|
+
* the global state, and rendered in place of the provider.
|
|
45
|
+
* @param prop.initialState Initial content of the global state.
|
|
46
|
+
* @param prop.ssrContext Server-side rendering (SSR) context.
|
|
47
|
+
* @param prop.stateProxy This option is useful for code
|
|
48
|
+
* splitting and SSR implementation:
|
|
49
|
+
* - If `true`, this provider instance will fetch and reuse the global state
|
|
50
|
+
* from a parent provider.
|
|
51
|
+
* - If `GlobalState` instance, it will be used by this provider.
|
|
52
|
+
* - If not given, a new `GlobalState` instance will be created and used.
|
|
53
|
+
*/
|
|
54
|
+
const GlobalStateProvider = t0 => {
|
|
55
|
+
const $ = _c(3);
|
|
56
|
+
const {
|
|
57
|
+
children,
|
|
58
|
+
...rest
|
|
59
|
+
} = t0;
|
|
60
|
+
const [localState, setLocalState] = useState();
|
|
61
|
+
let state;
|
|
62
|
+
if ("stateProxy" in rest && rest.stateProxy) {
|
|
63
|
+
if (localState) {
|
|
64
|
+
setLocalState(undefined);
|
|
65
|
+
}
|
|
66
|
+
if (rest.stateProxy === true) {
|
|
67
|
+
const gs = use(Context);
|
|
68
|
+
if (!gs) {
|
|
69
|
+
throw Error("Missing GlobalStateProvider");
|
|
70
|
+
}
|
|
71
|
+
state = gs;
|
|
72
|
+
} else {
|
|
73
|
+
state = rest.stateProxy;
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
if (localState) {
|
|
77
|
+
state = localState;
|
|
78
|
+
} else {
|
|
79
|
+
const {
|
|
80
|
+
initialState,
|
|
81
|
+
ssrContext
|
|
82
|
+
} = rest;
|
|
83
|
+
state = new GlobalState(typeof initialState === "function" ? initialState() : initialState, ssrContext);
|
|
84
|
+
setLocalState(state);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
let t1;
|
|
88
|
+
if ($[0] !== children || $[1] !== state) {
|
|
89
|
+
t1 = /*#__PURE__*/_jsx(Context, {
|
|
90
|
+
value: state,
|
|
91
|
+
children: children
|
|
92
|
+
});
|
|
93
|
+
$[0] = children;
|
|
94
|
+
$[1] = state;
|
|
95
|
+
$[2] = t1;
|
|
96
|
+
} else {
|
|
97
|
+
t1 = $[2];
|
|
98
|
+
}
|
|
99
|
+
return t1;
|
|
100
|
+
};
|
|
101
|
+
export default GlobalStateProvider;
|
|
102
|
+
//# sourceMappingURL=GlobalStateProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GlobalStateProvider.js","names":["state"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\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 * Returns the GlobalState object from the context. In most cases you should use\n * other hooks, like useGlobalState(), etc. to interact with the global state,\n * instead of accessing the GlobalState object directly.\n */\nexport function useGlobalStateObject<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * Returns SSR context.\n * @param throwWithoutSsrContext - If _true_ (default), this hook will throw\n * if no SSR context is attached to the global state; set _false_ to not throw\n * in such case. In either case this hook will throw if the <GlobalStateProvider>\n * (hence the global state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent <GlobalStateProvider> in the rendered\n * React tree.\n * - If `throwWithoutSsrContext` is _true_ (default), and there is no SSR\n * context attached to the global state provided by <GlobalStateProvider>.\n */\nexport function useSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = useGlobalStateObject<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> = (NewStateProps<StateT, SsrContextT> | {\n stateProxy: GlobalState<StateT, SsrContextT> | true;\n}) & {\n children?: ReactNode;\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\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n\n if (rest.stateProxy === true) {\n const gs = use(Context);\n if (!gs) throw Error('Missing GlobalStateProvider');\n state = gs as GlobalState<StateT, SsrContextT>;\n } else state = rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";AAAA,SAEE,aAAa,EACb,GAAG,EACH,QAAQ,QACH,OAAO;AAAC,OAER,WAAW;AAAA;AAKlB,MAAM,OAAO,gBAAG,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,oBAAoB,GAGE;EACpC,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC;EAChC,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAO,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;EAGL,iCAA6B,KAA7B,SAA6B,GAA7B,IAA6B,GAA7B,EAA6B;EAE7B;IAAA;EAAA,IAAuB,oBAAoB,CAAoC,CAAC;EAChF,IAAI,CAAC,UAAoC,IAArC,sBAAqC;IACvC,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC;EAAC;EACzC,OACM,UAAU;AAAA;AAiBnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,mBAAmB,GAAG;EAAA;EAI1B;IAAA;IAAA;EAAA,MAAoE;EAIpE,oCAAoC,QAAQ,CAAM,CAAC;EAE/CA,GAAA;EAMJ,IAAI,YAAY,IAAI,IAAoC,IAA3B,IAAI,WAAuB;IACtD,IAAI,UAAU;MAAE,aAAa,CAAC,SAAS,CAAC;IAAA;IAExC,IAAI,IAAI,WAAW,KAAK,IAAI;MAC1B,WAAW,GAAG,CAAC,OAAO,CAAC;MACvB,IAAI,CAAC,EAAE;QAAE,MAAM,KAAK,CAAC,6BAA6B,CAAC;MAAC;MACpD,MAAAA,CAAA,CAAQ,EAAE;IAAL;MACA,MAAAA,CAAA,CAAQ,IAAI,WAAW;IAAlB;EAAmB;IAC1B,IAAI,UAAU;MACnB,MAAAA,CAAA,CAAQ,UAAU;IAAb;MAEL;QAAA;QAAA;MAAA,IAGI,IAAI;MAER,MAAAA,CAAA,CAAQA,GAAA,CAAI,WAAW,CACrB,OAAO,YAAY,KAAK,UAA4D,GAA9C,YAAY,CAAiC,CAAC,GAApF,YAAoF,EACpF,UACF,CAAC;MAED,aAAa,CAAC,KAAK,CAAC;IAAA;EACrB;EAAA;EAAA;IAEM,uBAAC,OAAO;MAAQA,KAAK,EAAL,KAAK;MAAA,UAAG;IAAQ,CAAU,CAAC;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OAA3C,EAA2C;AAAA,CACnD;AAED,eAAe,mBAAmB","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SsrContext.js","names":[],"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":"AAAA,eAAe,MAAM,UAAU,CAAS;EACtC,KAAK,GAAY,KAAK;EAEtB,OAAO,GAAyB,EAAE;EAElC,WAAW,CAAQ,KAAc,EAAE;IAAA,KAAhB,KAAc,GAAd,KAAc;EAAI;AACvC","ignoreList":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import GlobalState from "./GlobalState.js";
|
|
2
|
-
import GlobalStateProvider, {
|
|
2
|
+
import GlobalStateProvider, { useGlobalStateObject, useSsrContext } from "./GlobalStateProvider.js";
|
|
3
3
|
import SsrContext from "./SsrContext.js";
|
|
4
4
|
import useAsyncCollection from "./useAsyncCollection.js";
|
|
5
5
|
import { loadAsyncData, newAsyncDataEnvelope, useAsyncData } from "./useAsyncData.js";
|
|
6
6
|
import useGlobalState from "./useGlobalState.js";
|
|
7
|
-
export { GlobalState, GlobalStateProvider, SsrContext,
|
|
7
|
+
export { GlobalState, GlobalStateProvider, SsrContext, loadAsyncData, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, useGlobalStateObject, useSsrContext };
|
|
8
8
|
|
|
9
9
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
10
10
|
|
|
@@ -15,13 +15,13 @@ const api = {
|
|
|
15
15
|
GlobalState,
|
|
16
16
|
GlobalStateProvider,
|
|
17
17
|
SsrContext,
|
|
18
|
-
getGlobalState,
|
|
19
|
-
getSsrContext,
|
|
20
18
|
loadAsyncData,
|
|
21
19
|
newAsyncDataEnvelope,
|
|
22
20
|
useAsyncCollection,
|
|
23
21
|
useAsyncData,
|
|
24
|
-
useGlobalState
|
|
22
|
+
useGlobalState,
|
|
23
|
+
useGlobalStateObject,
|
|
24
|
+
useSsrContext
|
|
25
25
|
};
|
|
26
26
|
export function withGlobalStateType() {
|
|
27
27
|
return api;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n useGlobalStateObject,\n useSsrContext,\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 LoadAsyncDataI,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} 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 GlobalState,\n GlobalStateProvider,\n SsrContext,\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateI,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\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 GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n SsrContext: typeof SsrContext<StateT>;\n loadAsyncData: LoadAsyncDataI<StateT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n useGlobalStateObject: typeof useGlobalStateObject<StateT, SsrContextT>;\n useSsrContext: typeof useSsrContext<SsrContextT>;\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 loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api;\n}\n"],"mappings":"OAAO,WAAW;AAAA,OAEX,mBAAmB,IACxB,oBAAoB,EACpB,aAAa;AAAA,OAGR,UAAU;AAAA,OAEV,kBAAkB;AAAA,SAavB,aAAa,EACb,oBAAoB,EACpB,YAAY;AAAA,OAGP,cAAc;AAYrB,SAIE,WAAW,EACX,mBAAmB,EACnB,UAAU,EAOV,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,oBAAoB,EACpB,aAAa;;AAGf;;AAiBA,MAAM,GAAG,GAAG;EACV;EACA;EACA;EACA,WAAW;EACX,mBAAmB;EACnB,UAAU;EACV,aAAa;EACb,oBAAoB;EACpB,kBAAkB;EAClB,YAAY;EACZ,cAAc;EACd,oBAAoB;EACpB;AACF,CAAC;AAED,OAAO,SAAS,mBAAmB,GAGL;EAC5B,OAAO,GAAG;AACZ","ignoreList":[]}
|