@dr.pogodin/react-global-state 0.9.3 → 0.10.0-alpha.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.
Files changed (55) hide show
  1. package/README.md +3 -328
  2. package/build/GlobalState.d.ts +75 -0
  3. package/build/GlobalState.js +193 -0
  4. package/build/GlobalStateProvider.d.ts +55 -0
  5. package/build/GlobalStateProvider.js +103 -0
  6. package/build/SsrContext.d.ts +6 -0
  7. package/build/SsrContext.js +10 -0
  8. package/build/index.d.ts +8 -0
  9. package/build/index.js +23 -0
  10. package/build/{module/useAsyncCollection.js → useAsyncCollection.d.ts} +16 -23
  11. package/build/useAsyncCollection.js +14 -0
  12. package/build/useAsyncData.d.ts +76 -0
  13. package/build/useAsyncData.js +150 -0
  14. package/build/{module/useGlobalState.js → useGlobalState.d.ts} +11 -62
  15. package/build/useGlobalState.js +49 -0
  16. package/build/utils.d.ts +31 -0
  17. package/build/{node/utils.js → utils.js} +11 -17
  18. package/build/withGlobalStateType.d.ts +39 -0
  19. package/build/withGlobalStateType.js +55 -0
  20. package/package.json +48 -27
  21. package/src/GlobalState.ts +279 -0
  22. package/src/GlobalStateProvider.tsx +116 -0
  23. package/src/SsrContext.ts +11 -0
  24. package/src/index.ts +33 -0
  25. package/{build/node/useAsyncCollection.js → src/useAsyncCollection.ts} +58 -25
  26. package/src/useAsyncData.ts +287 -0
  27. package/src/useGlobalState.ts +158 -0
  28. package/src/utils.ts +59 -0
  29. package/src/withGlobalStateType.ts +118 -0
  30. package/tsconfig.json +9 -0
  31. package/build/module/GlobalState.js +0 -191
  32. package/build/module/GlobalState.js.map +0 -1
  33. package/build/module/GlobalStateProvider.js +0 -81
  34. package/build/module/GlobalStateProvider.js.map +0 -1
  35. package/build/module/index.js +0 -12
  36. package/build/module/index.js.map +0 -1
  37. package/build/module/useAsyncCollection.js.map +0 -1
  38. package/build/module/useAsyncData.js +0 -206
  39. package/build/module/useAsyncData.js.map +0 -1
  40. package/build/module/useGlobalState.js.map +0 -1
  41. package/build/module/utils.js +0 -23
  42. package/build/module/utils.js.map +0 -1
  43. package/build/node/GlobalState.js +0 -174
  44. package/build/node/GlobalState.js.map +0 -1
  45. package/build/node/GlobalStateProvider.js +0 -88
  46. package/build/node/GlobalStateProvider.js.map +0 -1
  47. package/build/node/index.js +0 -56
  48. package/build/node/index.js.map +0 -1
  49. package/build/node/useAsyncCollection.js.map +0 -1
  50. package/build/node/useAsyncData.js +0 -211
  51. package/build/node/useAsyncData.js.map +0 -1
  52. package/build/node/useGlobalState.js +0 -114
  53. package/build/node/useGlobalState.js.map +0 -1
  54. package/build/node/utils.js.map +0 -1
  55. package/index.d.ts +0 -70
package/README.md CHANGED
@@ -4,337 +4,12 @@
4
4
  [![NPM monthly downloads](https://img.shields.io/npm/dm/@dr.pogodin/react-global-state)](https://www.npmjs.com/package/@dr.pogodin/react-global-state)
5
5
  [![CircleCI](https://dl.circleci.com/status-badge/img/gh/birdofpreyru/react-global-state/tree/master.svg?style=shield)](https://app.circleci.com/pipelines/github/birdofpreyru/react-global-state)
6
6
  [![GitHub Repo stars](https://img.shields.io/github/stars/birdofpreyru/react-global-state?style=social)](https://github.com/birdofpreyru/react-global-state)
7
+ [![Dr. Pogodin Studio](https://raw.githubusercontent.com/birdofpreyru/react-global-state/master/.README/logo-dr-pogodin-studio.svg)](https://dr.pogodin.studio/docs/react-global-state)
7
8
 
8
9
  State of the art approach to the global state and asynchronous data management
9
10
  in React applications, powered by hooks and Context API. Simple, efficient, with
10
11
  full server-side rendering (SSR) support.
11
12
 
12
- [Library Reference](https://dr.pogodin.studio/docs/react-global-state/index.html) •
13
- [Blog Article](https://dr.pogodin.studio/dev-blog/the-global-state-in-react-designed-right)
13
+ [⇒ Documentation ⇐](https://dr.pogodin.studio/docs/react-global-state/index.html)
14
14
 
15
- [![Sponsor](.README/sponsor.png)](https://github.com/sponsors/birdofpreyru)
16
-
17
- ### Motivation
18
-
19
- The motivation and vision is to bring to the table all useful features
20
- of Redux, without related development overheads, like the amount of required
21
- boilerplate code, and the efforts needed to design and maintain actions
22
- and reducers.
23
-
24
- With this library, the introduction of a datum (data piece), shared across
25
- different application components, is as easy as using the local React state:
26
-
27
- ```jsx
28
- function SampleReactComponent() {
29
- const [data, setData] = useGlobalState('data.storage.path', initialValue);
30
-
31
- /* `data` value can be updating by calling `setData(newData)` anywhere inside
32
- * the component code, including inside hooks like `useEffect(..)` or some
33
- * event handlers. */
34
-
35
- return /* Some JSX markup. */;
36
- }
37
- ```
38
-
39
- Relying on async data, e.g. loading into the state data from a 3-rd party API,
40
- is the same easy:
41
-
42
- ```jsx
43
- async function loader() {
44
-
45
- /* Some async operation to get data, like a call to a 3-rd party API. */
46
-
47
- return data;
48
- }
49
-
50
- function SampleReactComponent() {
51
- const { data, loading, timestamp } = useAsyncData('data.envelope.path', loader);
52
-
53
- /* `data` holds the data loaded into the global state, if they are fresh enough;
54
- * `loading` signals that data loading (or silent re-loading) is in-progress;
55
- * `timestamp` is the timestamp of currently loaded `data`. */
56
-
57
- return /* Some JSX markup. */
58
- }
59
- ```
60
- ⇑ Behind the scene, the library takes care about updating the component
61
- when the data loading starts and ends, also about the timestamps, automatic
62
- reloading, and garbage collection of aged data.
63
-
64
- Related closely to async data is the server-side rendering (SSR). This library
65
- takes it into account, and provides a flexible way to implement SSR with loading
66
- of some, or all async data at the server side.
67
-
68
- ### Setup
69
-
70
- 1. <a name="base-setup"></a> The base setup is simple: just wrap your app into
71
- the `<GlobalStateProvider>` component, provided by this library, and you'll
72
- be able to use any library hooks within its child hierarchy.
73
-
74
- ```jsx
75
- /* The minimal example of the library setup and usage. */
76
-
77
- import React from 'react';
78
- import {
79
- GlobalStateProvider,
80
- useAsyncData,
81
- useGlobalState,
82
- } from '@dr.pogodin/react-global-state';
83
-
84
- /* Example of component relying on the global state. */
85
-
86
- function SampleComponent() {
87
- const [value, setValue] = useGlobalState('sample.component', 0);
88
- return (
89
- <button onClick={() => setValue(1 + value)}>
90
- {value}
91
- </button>
92
- );
93
- }
94
-
95
- /* Example of component relying on async data in the global state. */
96
-
97
- async function sampleDataLoader() {
98
- return new Promise((resolve) => {
99
- setTimeout(() => resolve('Sample Data'), 500);
100
- });
101
- }
102
-
103
- function SampleAsyncComponent() {
104
- const { data, loading } = useAsyncData('sample.async-component', sampleDataLoader);
105
- return data;
106
- }
107
-
108
- /* Example of the root app component, providing the state. */
109
-
110
- export default function SampleApp() {
111
- return (
112
- <GlobalStateProvider>
113
- <SampleComponent />
114
- <SampleAsyncComponent />
115
- </GlobalStateProvider>
116
- );
117
- }
118
- ```
119
-
120
- Multiple, or nested `<GlobalStateProvider>` instances are allowed, and they
121
- will provide independent global states to its children (shadowing parent ones,
122
- in the case of nesting). However, the current SSR implementation assumes
123
- a single `<GlobalStateProvider>` at the app root. Multiple providers won't
124
- break it, but won't be a part of SSR data loading either.
125
-
126
- This setup is fine to run both at the client, and at the server-side, but
127
- in the case of server-side rendering, the library won't run any async data
128
- fetching, thus rendering pages with the initial global state; e.g. in
129
- the example above the `<SampleAsyncComponent>` will be rendered as an empty
130
- node, as `data` will be `undefined`, and `loading` will be `false`.
131
- To handle SSR better, and to have `<SampleAsyncComponent>` rendered as
132
- `Sample Data` even at the server-side, you need the following, a bit more
133
- complex, setup.
134
-
135
- 2. Advanced setup with the server-side rendering support is demonstrated below,
136
- assuming that `<SampleComponent>`, `sampleDataLoader(..)`,
137
- and `<SampleAsyncComponent>` are defined the same way as in the previous
138
- example, and `<SampleApp>` component itself does not include
139
- the `<GlobalStateProvider>`, i.e.
140
-
141
- ```jsx
142
- export default function SampleApp() {
143
- return (
144
- <React.Fragment>
145
- <SampleComponent />
146
- <SampleAsyncComponent />
147
- </React.Fragment>
148
- );
149
- }
150
- ```
151
-
152
- The server-side rendering code becomes:
153
-
154
- ```jsx
155
- /* Server-sider rendering. */
156
-
157
- import React from 'react';
158
- import ReactDOM from 'react-dom/server';
159
-
160
- import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
161
-
162
- import SampleApp from 'path/to/app';
163
-
164
- // As you want to keep server latency within a reason, it is a good idea
165
- // to limit the maximum number of SSR rounds, or the maximum SSR time, or
166
- // both, and perform any async operations which took too long at the client
167
- // side.
168
- const MAX_SSR_ROUNDS = 3;
169
- const SSR_TIMEOUT = 1000; // 1 second (in milliseconds).
170
-
171
- async function renderServerSide() {
172
- let render;
173
- const start = Date.now();
174
- const ssrContext = { state: {} };
175
- for (let round = 0; round < MAX_SSR_ROUNDS; round += 1) {
176
- // SSR round.
177
- render = ReactDOM.renderToString((
178
- <GlobalStateProvider
179
- initialState={ssrContext.state}
180
- ssrContext={ssrContext}
181
- >
182
- <SampleApp />
183
- </GlobalStateProvider>
184
- ));
185
-
186
- // SSR round did not altered the global state: we are done.
187
- if (!ssrContext.dirty) break;
188
-
189
- // Waiting for pending async operations to complete.
190
- const timeout = SSR_TIMEOUT + start - Date.now();
191
- const ok = timeout > 0 && await Promise.race([
192
- Promise.allSettled(ssrContext.pending),
193
- new Promise((x) => setTimeout(() => x(false), timeout)),
194
- ]);
195
- if (!ok) break; // SSR timeout.
196
- }
197
- return { render, state: ssrContext.state };
198
- }
199
- ```
200
- &uArr; When `ssrContext` property is passed into the `<GlobalStateProvider>`,
201
- the corresponding global state object switches into the SSR mode. In this mode,
202
- if the app rendering modifies the state, the `ssrContext.dirty` flag is set
203
- `true`, and for any async operations, triggered by the library hooks,
204
- corresponding promises are added into the `ssrContext.pending` array.
205
- Thus, the block of code
206
- ```js
207
- if (!ssrContext.dirty) break;
208
-
209
- const timeout = SSR_TIMEOUT + start - Date.now();
210
- const ok = timeout > 0 && await Promise.race([
211
- Promise.allSettled(ssrContext.pending),
212
- new Promise((x) => setTimeout(() => x(false), timeout)),
213
- ]);
214
- if (!ok) break;
215
- ```
216
- in the case when last rendering pass triggered async operations, it waits
217
- for them to complete, and allows the rendering pass to be redone
218
- with the new initial value of the global state, which is written to
219
- `ssrContext.state` in this case. If no updates to the state happened
220
- in the last rendering pass, this block breaks out of the loop, leaving
221
- to you in the `render` variable the HTML markup to send to the client,
222
- and in the `ssrContext.state` the initial value of the global state to use
223
- for app initialization at the client side.
224
-
225
- The outer `for` loop serves to protect against possible long re-rendering
226
- loops: if after several re-renders the state has not become stable, it is
227
- fine to send to the client side the latest render and state results, and
228
- finalize the rest of rendering at the client side. Similarly, the timeout
229
- condition interrupts SSR and cause the code to serve the current render
230
- and state, if any pending async operation takes too long, thus compromising
231
- server latency.
232
-
233
- In case when some async operations are too long to wait for them during SSR,
234
- the async hooks accept `noSSR` option, to be ignored during SSR. Additional
235
- option is to wrap the rendering cycle into a timeout race codition, and if
236
- the desired rendering time has bit hit, the rendering loop can be interrupted,
237
- and the latest render and state can be sent to the client side.
238
-
239
- The corresponding client-side rendering is simple, just pass the state
240
- calculated during the server-side rendering into the `initialState` prop
241
- of `<GlobalStateProvider>` at the client side:
242
-
243
- ```jsx
244
- /* Client-side rendering. */
245
-
246
- import React from 'react';
247
- import ReactDOM from 'react-dom';
248
-
249
- import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
250
-
251
- import SampleApp from 'path/to/app';
252
-
253
- function renderClientSide(stateFromServerSide) {
254
- ReactDOM.hydrate((
255
- <GlobalStateProvider initialState={stateFromServerSide}>
256
- <SampleApp />
257
- </GlobalStateProvider>
258
- ), document.getElementById('your-react-view'));
259
- }
260
- ```
261
-
262
- ### Frequently Asked Questions
263
-
264
- - _Does React Global State library avoid unnecessary component re-renders when values updated in the global state are irrelevant to those components?_
265
-
266
- Yes, it does avoid unnecessary re-renders of the component tree. A component
267
- relying on `some.path` in the global state is re-rendered only when the value
268
- at this path, or its sub-path has changed; _i.e._ it will be re-rendered if
269
- the value at `some.path` has changed, and it will be re-rendered if the value
270
- at `some.path.sub.path` has changed.
271
-
272
- - _How would you describe your use case compared to another React global state library, e.g. [Valtio](https://www.npmjs.com/package/valtio)?_
273
-
274
- 1. React Global State is designed to follow the standard React API as close
275
- as possible. _E.g._ if some component relies on the local state:
276
- ```jsx
277
- const [value, setValue] = useState(initialState);
278
- ```
279
- to move that value to the global state (or _vice versa_) one only needs to
280
- replace the hook with
281
- ```jsx
282
- const [value, setValue] = useGlobalState(path, initialState);
283
- ```
284
- The [useGlobalState()] hook takes care to follow all edge cases of the
285
- standard [useState()]: `setValue` setter identity is stable (does not
286
- change on re-renders), functional updates and lazy initial state are
287
- supported.
288
-
289
- Other libraries tend to re-invent the wheel, introducing their own APIs,
290
- which (i) should be learned and understood; (ii) do complicate migration
291
- of components between the local and global state, should it be needed in
292
- a course of app development / prototyping.
293
-
294
- 2. When it comes to async data in the global state other libraries tend to
295
- offer only a very basic supported, often relying on experimental or internal
296
- React mechanics.
297
-
298
- React Global State, [useAsyncData()] and [useAsyncCollection()] hooks in
299
- particular, implements async data fetching and management features: when
300
- multiple components use these hooks to load async data to the same global
301
- state path the library takes care to do the actual loading just once, and
302
- then keep the data without reloading until their age reaches (configurable)
303
- max age. There is an automated garbage collection of expired, non-used
304
- async data from the global state; there is server-side rendering (SSR)
305
- support, with suggested high-level setup taking care that all async data
306
- loaded using [useAsyncData()] and [useAsyncCollection()] hooks will be
307
- automatically loaded and used in server-side renders (still allowing to
308
- opt-out of that for individual hooks, and timeout server-side fetching of
309
- data that take too long to arrive, in which case the library will fetch
310
- such data client-side). It does not rely on experimental React APIs to
311
- achieve its functionality, it only uses current public APIs.
312
-
313
- For me the support of async data fetching into the global state and their
314
- further management with out-of-the-box SSR support was the primary
315
- motivation to create React Global State. There are many other global state
316
- React libraries, but I was not able to find any that would cover the async
317
- data handling with that ease I believed was possible. The secondary
318
- motivation was that existing global state libraries either had
319
- the shortcoming of unnecessary component re-renders when data irrelevant
320
- to them where updated in the global state, or introduced their
321
- own APIs, where following the standard React APIs for local state looks
322
- to me a way more convenient approach.
323
-
324
- - _Is React Global State library production ready (considering the current version number 0.y.z)?_
325
-
326
- Yes. I personally use it in production for all my commercial and personal
327
- React projects for over an year. I just don't feel like to call it v1 until
328
- a reasonable adoption by 3rd party developers, and any API improvements that
329
- may come out of community experience.
330
-
331
- [Library Reference](https://dr.pogodin.studio/docs/react-global-state/index.html) &bull;
332
- [Blog Article](https://dr.pogodin.studio/dev-blog/the-global-state-in-react-designed-right)
333
-
334
- [useAsyncCollection()]: https://dr.pogodin.studio/docs/react-global-state/docs/api/hooks/useasynccollection
335
- [useAsyncData()]: https://dr.pogodin.studio/docs/react-global-state/docs/api/hooks/useasyncdata
336
- [useGlobalState()]: https://dr.pogodin.studio/docs/react-global-state/docs/api/hooks/useglobalstate
337
- [useState()]: https://reactjs.org/docs/hooks-reference.html#usestate
338
-
339
- [functional updates]: https://reactjs.org/docs/hooks-reference.html#functional-updates
340
- [lazy initial state]: https://reactjs.org/docs/hooks-reference.html#functional-updates
15
+ [![Sponsor](https://raw.githubusercontent.com/birdofpreyru/react-global-state/master/.README/sponsor.svg)](https://github.com/sponsors/birdofpreyru)
@@ -0,0 +1,75 @@
1
+ import SsrContext from './SsrContext';
2
+ import { type CallbackT, type TypeLock, type ValueAtPathT, type ValueOrInitializerT } from './utils';
3
+ type GetOptsT<T> = {
4
+ initialState?: boolean;
5
+ initialValue?: ValueOrInitializerT<T>;
6
+ };
7
+ export default class GlobalState<StateT> {
8
+ #private;
9
+ readonly ssrContext?: SsrContext<StateT>;
10
+ /**
11
+ * Creates a new global state object.
12
+ * @param initialState Intial global state content.
13
+ * @param ssrContext Server-side rendering context.
14
+ */
15
+ constructor(initialState: StateT, ssrContext?: SsrContext<StateT>);
16
+ /**
17
+ * Gets entire state, the same way as .get(null, opts) would do.
18
+ * @param opts.initialState
19
+ * @param opts.initialValue
20
+ */
21
+ getEntireState(opts?: GetOptsT<StateT>): StateT;
22
+ /**
23
+ * Notifies all connected state watchers that a state update has happened.
24
+ */
25
+ private notifyStateUpdate;
26
+ /**
27
+ * Sets entire state, the same way as .set(null, value) would do.
28
+ * @param value
29
+ */
30
+ setEntireState(value: StateT): StateT;
31
+ /**
32
+ * Gets current or initial value at the specified "path" of the global state.
33
+ * @param path Dot-delimitered state path.
34
+ * @param options Additional options.
35
+ * @param options.initialState If "true" the value will be read
36
+ * from the initial state instead of the current one.
37
+ * @param options.initialValue If the value read from the "path" is
38
+ * "undefined", this "initialValue" will be returned instead. In such case
39
+ * "initialValue" will also be written to the "path" of the current global
40
+ * state (no matter "initialState" flag), if "undefined" is stored there.
41
+ * @return Retrieved value.
42
+ */
43
+ get(): StateT;
44
+ get<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;
45
+ get<Unlocked extends 0 | 1 = 0, ValueT = void>(path?: null | string, opts?: GetOptsT<TypeLock<Unlocked, never, ValueT>>): TypeLock<Unlocked, void, ValueT>;
46
+ /**
47
+ * Writes the `value` to given global state `path`.
48
+ * @param path Dot-delimitered state path. If not given, entire
49
+ * global state content is replaced by the `value`.
50
+ * @param value The value.
51
+ * @return Given `value` itself.
52
+ */
53
+ set<PathT extends null | string | undefined, ValueArgT extends ValueAtPathT<StateT, PathT, never>, ValueResT extends ValueAtPathT<StateT, PathT, void>>(path: PathT, value: ValueArgT): ValueResT;
54
+ set<Unlocked extends 0 | 1 = 0, ValueT = never>(path: null | string | undefined, value: TypeLock<Unlocked, never, ValueT>): TypeLock<Unlocked, void, ValueT>;
55
+ /**
56
+ * Unsubscribes `callback` from watching state updates; no operation if
57
+ * `callback` is not subscribed to the state updates.
58
+ * @param callback
59
+ * @throws if {@link SsrContext} is attached to the state instance: the state
60
+ * watching functionality is intended for client-side (non-SSR) only.
61
+ */
62
+ unWatch(callback: CallbackT): void;
63
+ /**
64
+ * Subscribes `callback` to watch state updates; no operation if
65
+ * `callback` is already subscribed to this state instance.
66
+ * @param callback It will be called without any arguments every
67
+ * time the state content changes (note, howhever, separate state updates can
68
+ * be applied to the state at once, and watching callbacks will be called once
69
+ * after such bulk update).
70
+ * @throws if {@link SsrContext} is attached to the state instance: the state
71
+ * watching functionality is intended for client-side (non-SSR) only.
72
+ */
73
+ watch(callback: CallbackT): void;
74
+ }
75
+ export {};
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _GlobalState_initialState, _GlobalState_watchers, _GlobalState_nextNotifierId, _GlobalState_currentState;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const lodash_1 = require("lodash");
16
+ const utils_1 = require("./utils");
17
+ const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
18
+ class GlobalState {
19
+ /**
20
+ * Creates a new global state object.
21
+ * @param initialState Intial global state content.
22
+ * @param ssrContext Server-side rendering context.
23
+ */
24
+ constructor(initialState, ssrContext) {
25
+ _GlobalState_initialState.set(this, void 0);
26
+ // TODO: It is tempting to replace watchers here by
27
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
28
+ // current watchers for emitting later, and this is not something
29
+ // Emitter supports right now.
30
+ _GlobalState_watchers.set(this, []);
31
+ _GlobalState_nextNotifierId.set(this, void 0);
32
+ _GlobalState_currentState.set(this, void 0);
33
+ __classPrivateFieldSet(this, _GlobalState_currentState, initialState, "f");
34
+ __classPrivateFieldSet(this, _GlobalState_initialState, initialState, "f");
35
+ if (ssrContext) {
36
+ /* eslint-disable no-param-reassign */
37
+ ssrContext.dirty = false;
38
+ ssrContext.pending = [];
39
+ ssrContext.state = __classPrivateFieldGet(this, _GlobalState_currentState, "f");
40
+ /* eslint-enable no-param-reassign */
41
+ this.ssrContext = ssrContext;
42
+ }
43
+ if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
44
+ /* eslint-disable no-console */
45
+ let msg = 'New ReactGlobalState created';
46
+ if (ssrContext)
47
+ msg += ' (SSR mode)';
48
+ console.groupCollapsed(msg);
49
+ console.log('Initial state:', (0, lodash_1.cloneDeep)(initialState));
50
+ console.groupEnd();
51
+ /* eslint-enable no-console */
52
+ }
53
+ }
54
+ /**
55
+ * Gets entire state, the same way as .get(null, opts) would do.
56
+ * @param opts.initialState
57
+ * @param opts.initialValue
58
+ */
59
+ getEntireState(opts) {
60
+ let state = (opts === null || opts === void 0 ? void 0 : opts.initialState) ? __classPrivateFieldGet(this, _GlobalState_initialState, "f") : __classPrivateFieldGet(this, _GlobalState_currentState, "f");
61
+ if (state !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined)
62
+ return state;
63
+ const iv = opts.initialValue;
64
+ state = (0, lodash_1.isFunction)(iv) ? iv() : iv;
65
+ if (__classPrivateFieldGet(this, _GlobalState_currentState, "f") === undefined)
66
+ this.setEntireState(state);
67
+ return state;
68
+ }
69
+ /**
70
+ * Notifies all connected state watchers that a state update has happened.
71
+ */
72
+ notifyStateUpdate(path, value) {
73
+ if (process.env.NODE_ENV !== 'production' && (0, utils_1.isDebugMode)()) {
74
+ /* eslint-disable no-console */
75
+ const p = typeof path === 'string'
76
+ ? `"${path}"` : 'none (entire state update)';
77
+ console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
78
+ console.log('New value:', (0, lodash_1.cloneDeep)(value));
79
+ console.log('New state:', (0, lodash_1.cloneDeep)(__classPrivateFieldGet(this, _GlobalState_currentState, "f")));
80
+ console.groupEnd();
81
+ /* eslint-enable no-console */
82
+ }
83
+ if (this.ssrContext) {
84
+ this.ssrContext.dirty = true;
85
+ this.ssrContext.state = __classPrivateFieldGet(this, _GlobalState_currentState, "f");
86
+ }
87
+ else if (!__classPrivateFieldGet(this, _GlobalState_nextNotifierId, "f")) {
88
+ __classPrivateFieldSet(this, _GlobalState_nextNotifierId, setTimeout(() => {
89
+ __classPrivateFieldSet(this, _GlobalState_nextNotifierId, undefined, "f");
90
+ const watchers = [...__classPrivateFieldGet(this, _GlobalState_watchers, "f")];
91
+ for (let i = 0; i < watchers.length; ++i) {
92
+ watchers[i]();
93
+ }
94
+ }), "f");
95
+ }
96
+ }
97
+ /**
98
+ * Sets entire state, the same way as .set(null, value) would do.
99
+ * @param value
100
+ */
101
+ setEntireState(value) {
102
+ if (__classPrivateFieldGet(this, _GlobalState_currentState, "f") !== value) {
103
+ __classPrivateFieldSet(this, _GlobalState_currentState, value, "f");
104
+ this.notifyStateUpdate(null, value);
105
+ }
106
+ return value;
107
+ }
108
+ get(path, opts) {
109
+ if ((0, lodash_1.isNil)(path)) {
110
+ const res = this.getEntireState(opts);
111
+ return res;
112
+ }
113
+ const state = (opts === null || opts === void 0 ? void 0 : opts.initialState) ? __classPrivateFieldGet(this, _GlobalState_initialState, "f") : __classPrivateFieldGet(this, _GlobalState_currentState, "f");
114
+ let res = (0, lodash_1.get)(state, path);
115
+ if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined)
116
+ return res;
117
+ const iv = opts.initialValue;
118
+ res = (0, lodash_1.isFunction)(iv) ? iv() : iv;
119
+ if (!(opts === null || opts === void 0 ? void 0 : opts.initialState) || this.get(path) === undefined) {
120
+ this.set(path, res);
121
+ }
122
+ return res;
123
+ }
124
+ set(path, value) {
125
+ if ((0, lodash_1.isNil)(path))
126
+ return this.setEntireState(value);
127
+ if (value !== this.get(path)) {
128
+ const root = { state: __classPrivateFieldGet(this, _GlobalState_currentState, "f") };
129
+ let segIdx = 0;
130
+ let pos = root;
131
+ const pathSegments = (0, lodash_1.toPath)(`state.${path}`);
132
+ for (; segIdx < pathSegments.length - 1; segIdx += 1) {
133
+ const seg = pathSegments[segIdx];
134
+ const next = pos[seg];
135
+ if (Array.isArray(next))
136
+ pos[seg] = [...next];
137
+ else if ((0, lodash_1.isObject)(next))
138
+ pos[seg] = Object.assign({}, next);
139
+ else {
140
+ // We arrived to a state sub-segment, where the remaining part of
141
+ // the update path does not exist yet. We rely on lodash's set()
142
+ // function to create the remaining path, and set the value.
143
+ (0, lodash_1.set)(pos, pathSegments.slice(segIdx), value);
144
+ break;
145
+ }
146
+ pos = pos[seg];
147
+ }
148
+ if (segIdx === pathSegments.length - 1) {
149
+ pos[pathSegments[segIdx]] = value;
150
+ }
151
+ __classPrivateFieldSet(this, _GlobalState_currentState, root.state, "f");
152
+ this.notifyStateUpdate(path, value);
153
+ }
154
+ return value;
155
+ }
156
+ /**
157
+ * Unsubscribes `callback` from watching state updates; no operation if
158
+ * `callback` is not subscribed to the state updates.
159
+ * @param callback
160
+ * @throws if {@link SsrContext} is attached to the state instance: the state
161
+ * watching functionality is intended for client-side (non-SSR) only.
162
+ */
163
+ unWatch(callback) {
164
+ if (this.ssrContext)
165
+ throw new Error(ERR_NO_SSR_WATCH);
166
+ const watchers = __classPrivateFieldGet(this, _GlobalState_watchers, "f");
167
+ const pos = watchers.indexOf(callback);
168
+ if (pos >= 0) {
169
+ watchers[pos] = watchers[watchers.length - 1];
170
+ watchers.pop();
171
+ }
172
+ }
173
+ /**
174
+ * Subscribes `callback` to watch state updates; no operation if
175
+ * `callback` is already subscribed to this state instance.
176
+ * @param callback It will be called without any arguments every
177
+ * time the state content changes (note, howhever, separate state updates can
178
+ * be applied to the state at once, and watching callbacks will be called once
179
+ * after such bulk update).
180
+ * @throws if {@link SsrContext} is attached to the state instance: the state
181
+ * watching functionality is intended for client-side (non-SSR) only.
182
+ */
183
+ watch(callback) {
184
+ if (this.ssrContext)
185
+ throw new Error(ERR_NO_SSR_WATCH);
186
+ const watchers = __classPrivateFieldGet(this, _GlobalState_watchers, "f");
187
+ if (watchers.indexOf(callback) < 0) {
188
+ watchers.push(callback);
189
+ }
190
+ }
191
+ }
192
+ _GlobalState_initialState = new WeakMap(), _GlobalState_watchers = new WeakMap(), _GlobalState_nextNotifierId = new WeakMap(), _GlobalState_currentState = new WeakMap();
193
+ exports.default = GlobalState;
@@ -0,0 +1,55 @@
1
+ import { type ReactNode } from 'react';
2
+ import GlobalState from './GlobalState';
3
+ import SsrContext from './SsrContext';
4
+ import { type ValueOrInitializerT } from './utils';
5
+ /**
6
+ * Gets {@link GlobalState} instance from the context. In most cases
7
+ * you should use {@link useGlobalState}, and other hooks to interact with
8
+ * the global state, instead of accessing it directly.
9
+ * @return
10
+ */
11
+ export declare function getGlobalState<StateT>(): GlobalState<StateT>;
12
+ /**
13
+ * @category Hooks
14
+ * @desc Gets SSR context.
15
+ * @param throwWithoutSsrContext If `true` (default),
16
+ * this hook will throw if no SSR context is attached to the global state;
17
+ * set `false` to not throw in such case. In either case the hook will throw
18
+ * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
19
+ * @returns SSR context.
20
+ * @throws
21
+ * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
22
+ * in the rendered React tree.
23
+ * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
24
+ * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
25
+ */
26
+ export declare function getSsrContext<StateT>(throwWithoutSsrContext?: boolean): SsrContext<StateT> | undefined;
27
+ type NewStateProps<StateT> = {
28
+ initialState: ValueOrInitializerT<StateT>;
29
+ ssrContext?: SsrContext<StateT>;
30
+ };
31
+ type GlobalStateProviderProps<StateT> = {
32
+ children?: ReactNode;
33
+ } & (NewStateProps<StateT> | {
34
+ stateProxy: true | GlobalState<StateT>;
35
+ });
36
+ /**
37
+ * Provides global state to its children.
38
+ * @param prop.children Component children, which will be provided with
39
+ * the global state, and rendered in place of the provider.
40
+ * @param prop.initialState Initial content of the global state.
41
+ * @param prop.ssrContext Server-side rendering (SSR) context.
42
+ * @param prop.stateProxy This option is useful for code
43
+ * splitting and SSR implementation:
44
+ * - If `true`, this provider instance will fetch and reuse the global state
45
+ * from a parent provider.
46
+ * - If `GlobalState` instance, it will be used by this provider.
47
+ * - If not given, a new `GlobalState` instance will be created and used.
48
+ */
49
+ declare function GlobalStateProvider<StateT>({ children, ...rest }: GlobalStateProviderProps<StateT>): import("react/jsx-runtime").JSX.Element;
50
+ declare namespace GlobalStateProvider {
51
+ var defaultProps: {
52
+ children: undefined;
53
+ };
54
+ }
55
+ export default GlobalStateProvider;