kiss-for-react 1.0.3 → 2.0.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.
Files changed (155) hide show
  1. package/README.md +699 -156
  2. package/lib/cjs/ClassPersistor.js +177 -112
  3. package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
  4. package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
  5. package/lib/cjs/Esserializer/builtins.js +258 -0
  6. package/lib/cjs/Esserializer/constant.js +39 -131
  7. package/lib/cjs/Esserializer/deserializer.js +226 -313
  8. package/lib/cjs/Esserializer/general.js +91 -39
  9. package/lib/cjs/Esserializer/index.js +47 -43
  10. package/lib/cjs/Esserializer/serializer.js +168 -133
  11. package/lib/cjs/Evt.js +132 -0
  12. package/lib/cjs/Hooks.js +1472 -969
  13. package/lib/cjs/KissAction.js +4635 -1333
  14. package/lib/cjs/LoadPages.js +336 -0
  15. package/lib/cjs/Persistor.js +189 -120
  16. package/lib/cjs/ProcessPersistence.js +579 -262
  17. package/lib/cjs/Store.js +4278 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +88 -0
  20. package/lib/cjs/UserException.js +212 -218
  21. package/lib/cjs/Wait.js +309 -309
  22. package/lib/cjs/index.js +69 -42
  23. package/lib/cjs/server.js +54 -0
  24. package/lib/cjs/types/ClassPersistor.d.ts +143 -112
  25. package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
  26. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
  27. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  28. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
  29. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  30. package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
  31. package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
  32. package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
  33. package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
  34. package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
  35. package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
  36. package/lib/cjs/types/Esserializer/general.d.ts +28 -4
  37. package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
  38. package/lib/cjs/types/Esserializer/index.d.ts +33 -29
  39. package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
  40. package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
  41. package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
  42. package/lib/cjs/types/Evt.d.ts +124 -0
  43. package/lib/cjs/types/Evt.d.ts.map +1 -0
  44. package/lib/cjs/types/Hooks.d.ts +1174 -837
  45. package/lib/cjs/types/Hooks.d.ts.map +1 -1
  46. package/lib/cjs/types/KissAction.d.ts +5199 -1398
  47. package/lib/cjs/types/KissAction.d.ts.map +1 -1
  48. package/lib/cjs/types/LoadPages.d.ts +287 -0
  49. package/lib/cjs/types/LoadPages.d.ts.map +1 -0
  50. package/lib/cjs/types/Persistor.d.ts +187 -118
  51. package/lib/cjs/types/Persistor.d.ts.map +1 -1
  52. package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
  53. package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
  54. package/lib/cjs/types/Store.d.ts +2253 -1042
  55. package/lib/cjs/types/Store.d.ts.map +1 -1
  56. package/lib/cjs/types/StoreException.d.ts +97 -28
  57. package/lib/cjs/types/StoreException.d.ts.map +1 -1
  58. package/lib/cjs/types/StoreProvider.d.ts +80 -0
  59. package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
  60. package/lib/cjs/types/UserException.d.ts +178 -169
  61. package/lib/cjs/types/UserException.d.ts.map +1 -1
  62. package/lib/cjs/types/index.d.ts +12 -9
  63. package/lib/cjs/types/index.d.ts.map +1 -1
  64. package/lib/cjs/types/server.d.ts +12 -0
  65. package/lib/cjs/types/server.d.ts.map +1 -0
  66. package/lib/cjs/types/utils.d.ts +15 -1
  67. package/lib/cjs/types/utils.d.ts.map +1 -1
  68. package/lib/cjs/utils.js +45 -7
  69. package/lib/esm/ClassPersistor.mjs +177 -0
  70. package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
  71. package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
  72. package/lib/esm/Esserializer/builtins.mjs +254 -0
  73. package/lib/esm/Esserializer/constant.mjs +28 -0
  74. package/lib/esm/Esserializer/deserializer.mjs +221 -0
  75. package/lib/esm/Esserializer/general.mjs +81 -0
  76. package/lib/esm/Esserializer/index.mjs +43 -0
  77. package/lib/esm/Esserializer/serializer.mjs +164 -0
  78. package/lib/esm/Evt.mjs +151 -0
  79. package/lib/esm/Hooks.mjs +1446 -0
  80. package/lib/esm/KissAction.mjs +4689 -0
  81. package/lib/esm/LoadPages.mjs +340 -0
  82. package/lib/esm/Persistor.mjs +180 -0
  83. package/lib/esm/ProcessPersistence.mjs +581 -0
  84. package/lib/esm/Store.mjs +4400 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +80 -0
  87. package/lib/esm/{UserException.js → UserException.mjs} +240 -246
  88. package/lib/esm/{Wait.js → Wait.mjs} +309 -309
  89. package/lib/esm/index.mjs +12 -9
  90. package/lib/esm/server.mjs +23 -0
  91. package/lib/esm/types/ClassPersistor.d.ts +143 -112
  92. package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
  93. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
  94. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  95. package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
  96. package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  97. package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
  98. package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
  99. package/lib/esm/types/Esserializer/constant.d.ts +25 -49
  100. package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
  101. package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
  102. package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
  103. package/lib/esm/types/Esserializer/general.d.ts +28 -4
  104. package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
  105. package/lib/esm/types/Esserializer/index.d.ts +33 -29
  106. package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
  107. package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
  108. package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
  109. package/lib/esm/types/Evt.d.ts +124 -0
  110. package/lib/esm/types/Evt.d.ts.map +1 -0
  111. package/lib/esm/types/Hooks.d.ts +1174 -837
  112. package/lib/esm/types/Hooks.d.ts.map +1 -1
  113. package/lib/esm/types/KissAction.d.ts +5199 -1398
  114. package/lib/esm/types/KissAction.d.ts.map +1 -1
  115. package/lib/esm/types/LoadPages.d.ts +287 -0
  116. package/lib/esm/types/LoadPages.d.ts.map +1 -0
  117. package/lib/esm/types/Persistor.d.ts +187 -118
  118. package/lib/esm/types/Persistor.d.ts.map +1 -1
  119. package/lib/esm/types/ProcessPersistence.d.ts +197 -99
  120. package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
  121. package/lib/esm/types/Store.d.ts +2253 -1042
  122. package/lib/esm/types/Store.d.ts.map +1 -1
  123. package/lib/esm/types/StoreException.d.ts +97 -28
  124. package/lib/esm/types/StoreException.d.ts.map +1 -1
  125. package/lib/esm/types/StoreProvider.d.ts +80 -0
  126. package/lib/esm/types/StoreProvider.d.ts.map +1 -0
  127. package/lib/esm/types/UserException.d.ts +178 -169
  128. package/lib/esm/types/UserException.d.ts.map +1 -1
  129. package/lib/esm/types/index.d.ts +12 -9
  130. package/lib/esm/types/index.d.ts.map +1 -1
  131. package/lib/esm/types/server.d.ts +12 -0
  132. package/lib/esm/types/server.d.ts.map +1 -0
  133. package/lib/esm/types/utils.d.ts +15 -1
  134. package/lib/esm/types/utils.d.ts.map +1 -1
  135. package/lib/esm/utils.mjs +38 -0
  136. package/package.json +55 -31
  137. package/lib/cjs/UnmodifiableSetView.js +0 -53
  138. package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
  139. package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
  140. package/lib/esm/ClassPersistor.js +0 -112
  141. package/lib/esm/Esserializer/constant.js +0 -81
  142. package/lib/esm/Esserializer/deserializer.js +0 -307
  143. package/lib/esm/Esserializer/general.js +0 -34
  144. package/lib/esm/Esserializer/index.js +0 -39
  145. package/lib/esm/Esserializer/serializer.js +0 -130
  146. package/lib/esm/Hooks.js +0 -955
  147. package/lib/esm/KissAction.js +0 -1459
  148. package/lib/esm/Persistor.js +0 -113
  149. package/lib/esm/ProcessPersistence.js +0 -262
  150. package/lib/esm/Store.js +0 -1606
  151. package/lib/esm/StoreException.js +0 -69
  152. package/lib/esm/UnmodifiableSetView.js +0 -50
  153. package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
  154. package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
  155. package/lib/esm/utils.js +0 -3
package/lib/cjs/Hooks.js CHANGED
@@ -1,969 +1,1472 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useClearExceptionFor = exports.useExceptionFor = exports.useIsFailed = exports.useIsWaiting = exports.useDispatchSync = exports.useDispatchAll = exports.useDispatchAndWaitAll = exports.useDispatchAndWait = exports.useDispatch = exports.useDispatcher = exports.useStore = exports.useAllState = exports.useSelector = exports.useSelect = void 0;
4
- const react_1 = require("react");
5
- const StoreException_1 = require("./StoreException");
6
- const Store_1 = require("./Store");
7
- /**
8
- * Returns a part of the store state:
9
- *
10
- * ```ts
11
- * const name = useSelect((state: State) => state.user.name);
12
- * ```
13
- *
14
- * The component will rebuild only when the `name` changes, ignoring the
15
- * change in other parts of the state.
16
- *
17
- * Note: You can use `useSelect` and `useSelector` interchangeably.
18
- * Prefer `useSelect` because it's shorter.
19
- */
20
- function useSelect(selector) {
21
- // This ref will persist for the full lifetime of the component.
22
- let ref = (0, react_1.useRef)(undefined);
23
- // The initial value is the value selected from the current state in the store.
24
- let store = _useStoreFromContext();
25
- const [value, setValue] = (0, react_1.useState)(() => selector(store.state));
26
- // Only once when the component mounts.
27
- (0, react_1.useEffect)(() => {
28
- // We save in the ref:
29
- // - The selector
30
- // - The currently selected value
31
- // - The setValue function
32
- //
33
- // Whenever the state changes, the store will:
34
- // 1. Retrieve all refs
35
- // 2. Apply each selector to the current state to calculate the selected value.
36
- // 3. And compare the selected value with the last selected value.
37
- // 4. If it changed, it calls setValue.
38
- ref.current = new RefState([selector, value, setValue]);
39
- // Save the new ref.
40
- store._refStateHooks.add(ref);
41
- return () => {
42
- // When the component unmounts, delete the ref.
43
- store._refStateHooks.delete(ref);
44
- };
45
- }, []);
46
- return value;
47
- }
48
- exports.useSelect = useSelect;
49
- /**
50
- * Returns a part of the store state:
51
- *
52
- * ```ts
53
- * const name = useSelector((state: State) => state.user.name);
54
- * ```
55
- *
56
- * The component will rebuild only when the `name` changes, ignoring the
57
- * change in other parts of the state.
58
- *
59
- * Note: You can use `useSelect` and `useSelector` interchangeably.
60
- * Prefer `useSelect` because it's shorter.
61
- */
62
- function useSelector(selector) {
63
- return useSelect(selector);
64
- }
65
- exports.useSelector = useSelector;
66
- /**
67
- * Returns the whole store state:
68
- *
69
- * ```ts
70
- * const state = useAllState<State>();
71
- * const name = state.user.name;
72
- * ```
73
- *
74
- * While that's convenient, the above code will rebuild the component for all state changes,
75
- * no matter if the name changed or not. For this reason, prefer `useSelector`:
76
- *
77
- * ```ts
78
- * const name = useSelector((state: State) => state.user.name);
79
- * ```
80
- *
81
- * Now it will rebuild only when the name changes.
82
- */
83
- function useAllState() {
84
- return useSelect((state) => state);
85
- }
86
- exports.useAllState = useAllState;
87
- /**
88
- * You can get the store to use all dispatch and wait methods:
89
- *
90
- * - `dispatch` - Dispatches the action to the Redux store, to potentially change the state.
91
- * - `dispatchAndWait` - Dispatches an action and returns a promise that resolves when the action finishes.
92
- * - `dispatchSync` - Same as the regular dispatch, except it throws an error if the action is ASYNC.
93
- * - `waitCondition` - Waits until the state is in a given condition.
94
- * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
95
- * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
96
- * - `waitActionType` - Waits until an action of a given type is NOT in progress.
97
- * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
98
- * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
99
- *
100
- * Example:
101
- *
102
- * ```js
103
- * const store = useStore();
104
- * store.dispatch(new MyAction());
105
- * await store.dispatchAndWait(new MyAction());
106
- * store.dispatchSync(new MyAction());
107
- * await waitCondition((state) => state.user.name === "Bill");
108
- * await waitAllActionTypes(['BuyAction', 'SellAction']);
109
- * ```
110
- *
111
- * IMPORTANT:
112
- * The store `state` and other store methods are NOT available when you get the store with `useStore`.
113
- * - To get the state: `useSelect`
114
- * - To wait for actions: `useIsWaiting`
115
- * - To deal with exceptions: `useIsFailed`, `useExceptionFor` and `clearExceptionFor`
116
- *
117
- * See also:
118
- * - `useDispatch()` - Hook equivalent to `useStore().dispatch`
119
- * - `useDispatchAndWait` - Hook equivalent to `useStore().dispatchAndWait`
120
- * - `useDispatchSync` - Hook equivalent to `useStore().dispatchSync`
121
- */
122
- function useStore() {
123
- let store = _useStoreFromContext();
124
- return new StoreDispatchers(store);
125
- }
126
- exports.useStore = useStore;
127
- /**
128
- * @deprecated Use `useDispatch`. Note you also have `useDispatchAndWait` and `useDispatchSync`.
129
- */
130
- function useDispatcher() {
131
- return useDispatch();
132
- }
133
- exports.useDispatcher = useDispatcher;
134
- /**
135
- * Dispatches the action to the Redux store, to potentially change the state:
136
- *
137
- * ```ts
138
- * const dispatch = useDispatch();
139
- * dispatch(MyAction());
140
- * ```
141
- *
142
- * This also works:
143
- *
144
- * ```ts
145
- * const store = useStore();
146
- * dispatch(MyAction());
147
- * ```
148
- *
149
- * See also:
150
- * - `dispatchAll` which dispatches all given actions in parallel.
151
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
152
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
153
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
154
- */
155
- function useDispatch() {
156
- let store = _useStoreFromContext();
157
- return store.dispatch.bind(store);
158
- }
159
- exports.useDispatch = useDispatch;
160
- /**
161
- * Dispatches an action and returns a promise that resolves when the action finishes.
162
- * While the state change from the action's reducer will have been applied when the promise
163
- * resolves, other independent processes that the action may have started may still be in
164
- * progress.
165
- *
166
- * Usage:
167
- * ```ts
168
- * const dispatchAndWait = useDispatchAndWait();
169
- * await dispatchAndWait(new MyAction())`.
170
- * ```
171
- *
172
- * See also:
173
- * - `dispatch` which dispatches both sync and async actions.
174
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
175
- * - `dispatchAll` which dispatches all given actions in parallel.
176
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
177
- */
178
- function useDispatchAndWait() {
179
- let store = _useStoreFromContext();
180
- return store.dispatchAndWait.bind(store);
181
- }
182
- exports.useDispatchAndWait = useDispatchAndWait;
183
- /**
184
- * Dispatches all given actions in parallel, applying their reducers, and possibly changing
185
- * the store state. The actions may be sync or async. It returns a Promise that resolves when
186
- * ALL actions finish.
187
- *
188
- * ```ts
189
- * const dispatchAndWaitAll = useDispatchAndWaitAll();
190
- * await dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
191
- * ```
192
- *
193
- * Note: While the state change from the action's reducers will have been applied when the
194
- * Promise resolves, other independent processes that the action may have started may still
195
- * be in progress.
196
- *
197
- * See also:
198
- * - `dispatch` which dispatches both sync and async actions.
199
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
200
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
201
- * - `dispatchAll` which dispatches all given actions in parallel.
202
- */
203
- function useDispatchAndWaitAll() {
204
- let store = _useStoreFromContext();
205
- return store.dispatchAndWaitAll.bind(store);
206
- }
207
- exports.useDispatchAndWaitAll = useDispatchAndWaitAll;
208
- /**
209
- * Dispatches all given actions in parallel, applying their reducer, and possibly changing
210
- * the store state.
211
- *
212
- * ```ts
213
- * const dispatchAll = useDispatchAll();
214
- * dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
215
- * ```
216
- *
217
- * See also:
218
- * - `dispatch` which dispatches both sync and async actions.
219
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
220
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
221
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
222
- */
223
- function useDispatchAll() {
224
- let store = _useStoreFromContext();
225
- return store.dispatchAll.bind(store);
226
- }
227
- exports.useDispatchAll = useDispatchAll;
228
- /**
229
- * Dispatches the given action to the Redux store, to potentially change the state.
230
- *
231
- * This is exactly the same as the regular `dispatch`, except for the fact it
232
- * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
233
- * if any of its `reduce()` or `before()` methods return a Promise.
234
- *
235
- * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
236
- * action is SYNC, which means the state gets changed right after the dispatch call.
237
- *
238
- * See also:
239
- * - `dispatch` which dispatches both sync and async actions.
240
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
241
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
242
- * - `dispatchAll` which dispatches all given actions in parallel.
243
- */
244
- function useDispatchSync() {
245
- let store = _useStoreFromContext();
246
- return store.dispatchSync.bind(store);
247
- }
248
- exports.useDispatchSync = useDispatchSync;
249
- /**
250
- * You can use `isWaiting` and pass it an action `type`:
251
- * - It returns true if an ASYNC action of the specific type is currently being processed.
252
- * - It returns false if an ASYNC action of the specific type is NOT currently being processed.
253
- * - This is only useful for ASYNC actions, since it always returns `false` when the action is SYNC.
254
- *
255
- * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
256
- *
257
- * ```ts
258
- * const isWaiting = useIsWaiting(MyAction);
259
- * if (isWaiting) { // Show a spinner }
260
- * ```
261
- */
262
- function useIsWaiting(type) {
263
- return _useStoreSelector((store) => store.isWaiting(type));
264
- }
265
- exports.useIsWaiting = useIsWaiting;
266
- /**
267
- * Returns true if the given action `type` failed with an `UserException`.
268
- * Note: This method uses the EXACT action type. Subtypes are not considered.
269
- */
270
- function useIsFailed(type) {
271
- return _useStoreSelector((store) => store.isFailed(type));
272
- }
273
- exports.useIsFailed = useIsFailed;
274
- /**
275
- * Returns the `UserException` of the `type` that failed.
276
- * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
277
- */
278
- function useExceptionFor(type) {
279
- return _useStoreSelector((store) => store.exceptionFor(type));
280
- }
281
- exports.useExceptionFor = useExceptionFor;
282
- /**
283
- * Removes the exact given action `type` from the list of action types that failed.
284
- * Note it clears the EXACT given type. Subtypes are not considered.
285
- *
286
- * Even if you never call this method explicitly, just dispatching an action already clears that action type
287
- * from the list of failing action types. But you can call this method explicitly if you want to clear the
288
- * action type before it's used again.
289
- *
290
- * Usage:
291
- * ```ts
292
- * const clearExceptionFor = useClearExceptionFor();
293
- * clearExceptionFor(MyAction);
294
- * clearExceptionFor(AnotherAction);
295
- * ```
296
- */
297
- function useClearExceptionFor() {
298
- const store = _useStoreFromContext();
299
- return (type) => {
300
- store.clearExceptionFor(type);
301
- };
302
- }
303
- exports.useClearExceptionFor = useClearExceptionFor;
304
- function _useStoreSelector(selector) {
305
- // This ref will persist for the full lifetime of the component.
306
- let ref = (0, react_1.useRef)(undefined);
307
- // The initial value is the value selected from the current state in the store.
308
- let store = _useStoreFromContext();
309
- const [value, setValue] = (0, react_1.useState)(() => selector(store));
310
- // Only once when the component mounts.
311
- (0, react_1.useEffect)(() => {
312
- // We save in the ref:
313
- // - The selector
314
- // - The currently selected value
315
- // - The setValue function
316
- //
317
- // Whenever the state changes, the store will:
318
- // 1. Retrieve all refs
319
- // 2. Apply each selector to the current state to calculate the selected value.
320
- // 3. And compare the selected value with the last selected value.
321
- // 4. If it changed, it calls setValue.
322
- ref.current = new RefStore([selector, value, setValue]);
323
- // Save the new ref.
324
- store._refStoreHooks.add(ref);
325
- return () => {
326
- // When the component unmounts, delete the ref.
327
- store._refStoreHooks.delete(ref);
328
- };
329
- }, []);
330
- return value;
331
- }
332
- function _useStoreFromContext() {
333
- const context = (0, react_1.useContext)(Store_1.StoreContext);
334
- if (context === undefined) {
335
- throw new StoreException_1.StoreException('useStore must be used within a StoreProvider');
336
- }
337
- return context.store;
338
- }
339
- /**
340
- * Helper class that allows us to write:
341
- *
342
- * ```js
343
- * const store = useStore();
344
- * store.dispatch(new MyAction());
345
- * store.dispatchSync(new MyAction());
346
- * await store.dispatchAndWait(new MyAction());
347
- * ```
348
- */
349
- class StoreDispatchers {
350
- constructor(store) {
351
- this.store = store;
352
- }
353
- /**
354
- * Dispatches the action to the Redux store, to potentially change the state.
355
- */
356
- dispatch(action) {
357
- return this.store.dispatch(action);
358
- }
359
- /**
360
- * Dispatches an action and returns a promise that resolves when the action finishes.
361
- * While the state change from the action's reducer will have been applied when the promise
362
- * resolves, other independent processes that the action may have started may still be in
363
- * progress.
364
- *
365
- * Usage: `await store.dispatchAndWait(new MyAction())`.
366
- */
367
- dispatchAndWait(action) {
368
- return this.store.dispatchAndWait(action);
369
- }
370
- /**
371
- * Dispatches the given action to the Redux store, to potentially change the state.
372
- *
373
- * This is exactly the same as the regular `dispatch`, except for the fact it
374
- * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
375
- * if any of its `reduce()` or `before()` methods return a Promise.
376
- *
377
- * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
378
- * action is SYNC, which means the state gets changed right after the dispatch call.
379
- */
380
- dispatchSync(action) {
381
- return this.store.dispatchSync(action);
382
- }
383
- /**
384
- * Returns a promise which will resolve when the given state `condition` is true.
385
- * If the condition is already true when the method is called, the promise resolves immediately.
386
- *
387
- * You may also provide a `timeoutMillis`, which by default is 10 minutes. If you want, you
388
- * can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
389
- * To disable the timeout, make it 0 or -1.
390
- *
391
- * This method is useful in tests, and it returns the action which changed
392
- * the store state into the condition, in case you need it:
393
- *
394
- * ```typescript
395
- * let action = await store.waitCondition((state) => state.name == "Bill");
396
- * expect(action instanceof ChangeNameAction).toBe(true);
397
- *
398
- * This method is also eventually useful in production code, in which case you
399
- * should avoid waiting for conditions that may take a very long time to complete,
400
- * as checking the condition is an overhead to every state change.
401
- *
402
- * Examples:
403
- *
404
- * // Dispatches an actions that changes the state, then await for the state change:
405
- * expect(store.state.name, 'John')
406
- * dispatch(new ChangeNameAction("Bill"));
407
- * let action = await store.waitCondition((state) => state.name == "Bill");
408
- * expect(action instanceof ChangeNameAction).toBe(true);
409
- * expect(store.state.name, 'Bill');
410
- *
411
- * // Dispatches actions and wait until no actions are in progress.
412
- * dispatch(new BuyAction('IBM'));
413
- * dispatch(new BuyAction('TSLA'));
414
- * await waitAllActions([]);
415
- * expect(state.stocks, ['IBM', 'TSLA']);
416
- *
417
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
418
- * expect(store.state.portfolio, ['TSLA']);
419
- * dispatch(new BuyAction('IBM'));
420
- * dispatch(new SellAction('TSLA'));
421
- * await store.waitAllActionTypes([BuyAction, SellAction]);
422
- * expect(store.state.portfolio, ['IBM']);
423
- *
424
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
425
- * dispatch(new BuyAction('IBM'));
426
- * dispatch(new BuyAction('TSLA'));
427
- * await store.waitAllActions([]);
428
- * expect(store.state.portfolio.includes('IBM', 'TSLA')).toBe(false);
429
- *
430
- * // Dispatches two actions in PARALLEL and wait for them:
431
- * let action1 = new BuyAction('IBM');
432
- * let action2 = new SellAction('TSLA');
433
- * dispatch(action1);
434
- * dispatch(action2);
435
- * await store.waitAllActions([action1, action2]);
436
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
437
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
438
- *
439
- * // Dispatches two actions in SERIES and wait for them:
440
- * await dispatchAndWait(new BuyAction('IBM'));
441
- * await dispatchAndWait(new SellAction('TSLA'));
442
- * expect(store.state.portfolio.includes('IBM', 'TSLA')).toBe(false);
443
- *
444
- * // Wait until some action of a given type is dispatched.
445
- * dispatch(new DoALotOfStuffAction());
446
- * let action = store.waitActionType(ChangeNameAction);
447
- * expect(action instanceof ChangeNameAction).toBe(true);
448
- * expect(action.status.isCompletedOk).toBe(true);
449
- * expect(store.state.name, 'Bill');
450
- *
451
- * // Wait until some action of the given types is dispatched.
452
- * dispatch(new ProcessStocksAction());
453
- * let action = store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
454
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
455
- *
456
- * See also:
457
- * `waitCondition` - Waits until the state is in a given condition.
458
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
459
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
460
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
461
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
462
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
463
- */
464
- waitCondition(condition, timeoutMillis = null) {
465
- return this.store.waitCondition(condition, timeoutMillis);
466
- }
467
- /**
468
- * Returns a Promise that resolves when some actions meet the given `condition`.
469
- *
470
- * If `completeImmediately` is false (the default), this method will throw an error if the
471
- * condition was already true when the method was called. Otherwise, the promise will complete
472
- * immediately and throw no error.
473
- *
474
- * The `condition` is a function that takes the set of actions "in progress", as well as an
475
- * action that just entered the set (by being dispatched) or left the set (by finishing
476
- * dispatching). The function should return `true` when the condition is met, and `false`
477
- * otherwise. For example:
478
- *
479
- * ```ts
480
- * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
481
- * ```
482
- *
483
- * Important: Your condition function should NOT modify the set of actions.
484
- *
485
- * You get back the set of the actions being dispatched that met the condition, as well as
486
- * the action that triggered the condition by being added or removed from the set.
487
- *
488
- * Note: The condition is only checked when some action is dispatched or finishes dispatching.
489
- * It's not checked every time action statuses change.
490
- *
491
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
492
- * To disable the timeout, make it 0 or -1.
493
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
494
- *
495
- * Examples:
496
- *
497
- * ```ts
498
- * // Dispatches an actions that changes the state, then await for the state change:
499
- * expect(store.state.name).toBe('John');
500
- * dispatch(new ChangeNameAction("Bill"));
501
- * let action = await store.waitCondition((state) => state.name == "Bill");
502
- * expect(action instanceof ChangeNameAction).toBe(true);
503
- * expect(store.state.name).toBe('Bill');
504
- *
505
- * // Dispatches actions and wait until no actions are in progress.
506
- * dispatch(new BuyAction('IBM'));
507
- * dispatch(new BuyAction('TSLA'));
508
- * await waitAllActions();
509
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
510
- *
511
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
512
- * expect(store.state.portfolio).toEqual(['TSLA']);
513
- * dispatch(new BuyAction('IBM'));
514
- * dispatch(new SellAction('TSLA'));
515
- * await store.waitAllActionTypes([BuyAction, SellAction]);
516
- * expect(store.state.portfolio).toEqual(['IBM']);
517
- *
518
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
519
- * dispatch(new BuyAction('IBM'));
520
- * dispatch(new BuyAction('TSLA'));
521
- * await store.waitAllActions();
522
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
523
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
524
- *
525
- * // Dispatches two actions in PARALLEL and wait for them:
526
- * let action1 = new BuyAction('IBM');
527
- * let action2 = new SellAction('TSLA');
528
- * dispatch(action1);
529
- * dispatch(action2);
530
- * await store.waitAllActions([action1, action2]);
531
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
532
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
533
- *
534
- * // Dispatches two actions in SERIES and wait for them:
535
- * await dispatchAndWait(new BuyAction('IBM'));
536
- * await dispatchAndWait(new SellAction('TSLA'));
537
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
538
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
539
- *
540
- * // Wait until some action of a given type is dispatched.
541
- * dispatch(new DoALotOfStuffAction());
542
- * let action = await store.waitActionType(ChangeNameAction);
543
- * expect(action instanceof ChangeNameAction).toBe(true);
544
- * expect(action.status.isCompletedOk).toBe(true);
545
- * expect(store.state.name).toBe('Bill');
546
- *
547
- * // Wait until some action of the given types is dispatched.
548
- * dispatch(new ProcessStocksAction());
549
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
550
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
551
- * ```
552
- *
553
- * See also:
554
- * `waitCondition` - Waits until the state is in a given condition.
555
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
556
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
557
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
558
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
559
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
560
- *
561
- * You should only use this method in tests.
562
- */
563
- async waitActionCondition(
564
- //
565
- /// The condition receives the current actions in progress, and the action that triggered the condition.
566
- condition, {
567
- // If `completeImmediately` is `false` (the default), this method will throw an error if the
568
- // condition is already true when the method is called. Otherwise, the promise will complete
569
- // immediately and throw no error.
570
- completeImmediately = false,
571
- //
572
- // The maximum time to wait for the condition to be met. The default is 10 minutes.
573
- // To disable the timeout, make it 0 or -1.
574
- timeoutMillis = null, } = {}) {
575
- return this.store.waitActionCondition(condition, {
576
- completeImmediately: completeImmediately,
577
- timeoutMillis: timeoutMillis
578
- });
579
- }
580
- /**
581
- * Returns a promise that resolves when ALL given actions finished dispatching.
582
- *
583
- * If `completeImmediately` is false (the default), this method will throw an error if none
584
- * of the given actions are in progress when the method is called. Otherwise, the promise will
585
- * complete immediately and throw no error.
586
- *
587
- * However, if you don't provide any actions (empty list or `null`), the promise will complete
588
- * when ALL current actions in progress finish dispatching. In other words, when no actions are
589
- * currently in progress. In this case, if [completeImmediately] is `false`, the method will
590
- * throw an error if no actions are in progress when the method is called.
591
- *
592
- * Note: Waiting until no actions are in progress should only be done in test, never in
593
- * production, as it's very easy to create a deadlock. However, waiting for specific actions to
594
- * finish is safe in production, as long as you're waiting for actions you just dispatched.
595
- *
596
- * You may also provide a [timeoutMillis], which by default is 10 minutes.
597
- * To disable the timeout, make it 0 or -1.
598
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
599
- *
600
- * Examples:
601
- *
602
- * ```ts
603
- * // Dispatches an actions that changes the state, then await for the state change:
604
- * expect(store.state.name).toBe('John');
605
- * dispatch(new ChangeNameAction("Bill"));
606
- * let action = await store.waitCondition((state) => state.name == "Bill");
607
- * expect(action instanceof ChangeNameAction).toBe(true);
608
- * expect(store.state.name).toBe('Bill');
609
- *
610
- * // Dispatches actions and wait until no actions are in progress.
611
- * dispatch(new BuyAction('IBM'));
612
- * dispatch(new BuyAction('TSLA'));
613
- * await waitAllActions();
614
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
615
- *
616
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
617
- * expect(store.state.portfolio).toEqual(['TSLA']);
618
- * dispatch(new BuyAction('IBM'));
619
- * dispatch(new SellAction('TSLA'));
620
- * await store.waitAllActionTypes([BuyAction, SellAction]);
621
- * expect(store.state.portfolio).toEqual(['IBM']);
622
- *
623
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
624
- * dispatch(new BuyAction('IBM'));
625
- * dispatch(new BuyAction('TSLA'));
626
- * await store.waitAllActions();
627
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
628
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
629
- *
630
- * // Dispatches two actions in PARALLEL and wait for them:
631
- * let action1 = new BuyAction('IBM');
632
- * let action2 = new SellAction('TSLA');
633
- * dispatch(action1);
634
- * dispatch(action2);
635
- * await store.waitAllActions([action1, action2]);
636
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
637
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
638
- *
639
- * // Dispatches two actions in SERIES and wait for them:
640
- * await dispatchAndWait(new BuyAction('IBM'));
641
- * await dispatchAndWait(new SellAction('TSLA'));
642
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
643
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
644
- *
645
- * // Wait until some action of a given type is dispatched.
646
- * dispatch(new DoALotOfStuffAction());
647
- * let action = await store.waitActionType(ChangeNameAction);
648
- * expect(action instanceof ChangeNameAction).toBe(true);
649
- * expect(action.status.isCompletedOk).toBe(true);
650
- * expect(store.state.name).toBe('Bill');
651
- *
652
- * // Wait until some action of the given types is dispatched.
653
- * dispatch(new ProcessStocksAction());
654
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
655
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
656
- * ```
657
- *
658
- * See also:
659
- * `waitCondition` - Waits until the state is in a given condition.
660
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
661
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
662
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
663
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
664
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
665
- *
666
- * You should only use this method in tests.
667
- */
668
- waitAllActions(actions, { completeImmediately = false, timeoutMillis = null } = {}) {
669
- return this.store.waitAllActions(actions, {
670
- completeImmediately: completeImmediately,
671
- timeoutMillis: timeoutMillis
672
- });
673
- }
674
- /**
675
- * Returns a promise that completes when an action of the given type in NOT in progress
676
- * (it's not being dispatched):
677
- *
678
- * - If NO action of the given type is currently in progress when the method is called,
679
- * and `completeImmediately` is false (the default), this method will throw an error.
680
- *
681
- * - If NO action of the given type is currently in progress when the method is called,
682
- * and `completeImmediately` is true, the promise completes immediately, returns `null`,
683
- * and throws no error.
684
- *
685
- * - If an action of the given type is in progress, the promise completes when the action
686
- * finishes, and returns the action. You can use the returned action to check its `status`:
687
- *
688
- * ```dart
689
- * var action = await store.waitActionType(MyAction);
690
- * expect(action.status.originalError, isA<UserException>());
691
- * ```
692
- *
693
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
694
- * To disable the timeout, make it 0 or -1.
695
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
696
- *
697
- * Examples:
698
- *
699
- * ```ts
700
- * // Dispatches an actions that changes the state, then await for the state change:
701
- * expect(store.state.name).toBe('John');
702
- * dispatch(new ChangeNameAction("Bill"));
703
- * let action = await store.waitCondition((state) => state.name == "Bill");
704
- * expect(action instanceof ChangeNameAction).toBe(true);
705
- * expect(store.state.name).toBe('Bill');
706
- *
707
- * // Dispatches actions and wait until no actions are in progress.
708
- * dispatch(new BuyAction('IBM'));
709
- * dispatch(new BuyAction('TSLA'));
710
- * await waitAllActions();
711
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
712
- *
713
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
714
- * expect(store.state.portfolio).toEqual(['TSLA']);
715
- * dispatch(new BuyAction('IBM'));
716
- * dispatch(new SellAction('TSLA'));
717
- * await store.waitAllActionTypes([BuyAction, SellAction]);
718
- * expect(store.state.portfolio).toEqual(['IBM']);
719
- *
720
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
721
- * dispatch(new BuyAction('IBM'));
722
- * dispatch(new BuyAction('TSLA'));
723
- * await store.waitAllActions();
724
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
725
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
726
- *
727
- * // Dispatches two actions in PARALLEL and wait for them:
728
- * let action1 = new BuyAction('IBM');
729
- * let action2 = new SellAction('TSLA');
730
- * dispatch(action1);
731
- * dispatch(action2);
732
- * await store.waitAllActions([action1, action2]);
733
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
734
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
735
- *
736
- * // Dispatches two actions in SERIES and wait for them:
737
- * await dispatchAndWait(new BuyAction('IBM'));
738
- * await dispatchAndWait(new SellAction('TSLA'));
739
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
740
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
741
- *
742
- * // Wait until some action of a given type is dispatched.
743
- * dispatch(new DoALotOfStuffAction());
744
- * let action = await store.waitActionType(ChangeNameAction);
745
- * expect(action instanceof ChangeNameAction).toBe(true);
746
- * expect(action.status.isCompletedOk).toBe(true);
747
- * expect(store.state.name).toBe('Bill');
748
- *
749
- * // Wait until some action of the given types is dispatched.
750
- * dispatch(new ProcessStocksAction());
751
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
752
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
753
- * ```
754
- *
755
- * See also:
756
- * `waitCondition` - Waits until the state is in a given condition.
757
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
758
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
759
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
760
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
761
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
762
- *
763
- * You should only use this method in tests.
764
- */
765
- async waitActionType(actionType, { completeImmediately = false, timeoutMillis = null } = {}) {
766
- return this.store.waitActionType(actionType, {
767
- completeImmediately: completeImmediately,
768
- timeoutMillis: timeoutMillis
769
- });
770
- }
771
- /**
772
- * Returns a promise that completes when ALL actions of the given type are NOT in progress
773
- * (none of them is being dispatched):
774
- *
775
- * - If NO action of the given types is currently in progress when the method is called,
776
- * and `completeImmediately` is false (the default), this method will throw an error.
777
- *
778
- * - If NO action of the given type is currently in progress when the method is called,
779
- * and `completeImmediately` is true, the promise completes immediately and throws no error.
780
- *
781
- * - If any action of the given types is in progress, the promise completes only when
782
- * no action of the given types is in progress anymore.
783
- *
784
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
785
- * To disable the timeout, make it 0 or -1.
786
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
787
- *
788
- * Examples:
789
- *
790
- * ```ts
791
- * // Dispatches an actions that changes the state, then await for the state change:
792
- * expect(store.state.name).toBe('John');
793
- * dispatch(new ChangeNameAction("Bill"));
794
- * let action = await store.waitCondition((state) => state.name == "Bill");
795
- * expect(action instanceof ChangeNameAction).toBe(true);
796
- * expect(store.state.name).toBe('Bill');
797
- *
798
- * // Dispatches actions and wait until no actions are in progress.
799
- * dispatch(new BuyAction('IBM'));
800
- * dispatch(new BuyAction('TSLA'));
801
- * await waitAllActions();
802
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
803
- *
804
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
805
- * expect(store.state.portfolio).toEqual(['TSLA']);
806
- * dispatch(new BuyAction('IBM'));
807
- * dispatch(new SellAction('TSLA'));
808
- * await store.waitAllActionTypes([BuyAction, SellAction]);
809
- * expect(store.state.portfolio).toEqual(['IBM']);
810
- *
811
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
812
- * dispatch(new BuyAction('IBM'));
813
- * dispatch(new BuyAction('TSLA'));
814
- * await store.waitAllActions();
815
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
816
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
817
- *
818
- * // Dispatches two actions in PARALLEL and wait for them:
819
- * let action1 = new BuyAction('IBM');
820
- * let action2 = new SellAction('TSLA');
821
- * dispatch(action1);
822
- * dispatch(action2);
823
- * await store.waitAllActions([action1, action2]);
824
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
825
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
826
- *
827
- * // Dispatches two actions in SERIES and wait for them:
828
- * await dispatchAndWait(new BuyAction('IBM'));
829
- * await dispatchAndWait(new SellAction('TSLA'));
830
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
831
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
832
- *
833
- * // Wait until some action of a given type is dispatched.
834
- * dispatch(new DoALotOfStuffAction());
835
- * let action = await store.waitActionType(ChangeNameAction);
836
- * expect(action instanceof ChangeNameAction).toBe(true);
837
- * expect(action.status.isCompletedOk).toBe(true);
838
- * expect(store.state.name).toBe('Bill');
839
- *
840
- * // Wait until some action of the given types is dispatched.
841
- * dispatch(new ProcessStocksAction());
842
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
843
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
844
- * ```
845
- *
846
- * See also:
847
- * `waitCondition` - Waits until the state is in a given condition.
848
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
849
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
850
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
851
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
852
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
853
- *
854
- * You should only use this method in tests.
855
- */
856
- async waitAllActionTypes(actionTypes, { completeImmediately = false, timeoutMillis = null } = {}) {
857
- return this.store.waitAllActionTypes(actionTypes, {
858
- completeImmediately: completeImmediately,
859
- timeoutMillis: timeoutMillis
860
- });
861
- }
862
- /**
863
- * Returns a promise which will complete when ANY action of the given types FINISHES
864
- * dispatching. IMPORTANT: This method is different from the other similar methods, because
865
- * it does NOT complete immediately if no action of the given types is in progress. Instead,
866
- * it waits until an action of the given types finishes dispatching, even if they
867
- * were not yet in progress when the method was called.
868
- *
869
- * This method returns the action that completed the promise, which you can use to check
870
- * its `status`.
871
- *
872
- * It's useful when the actions you are waiting for are not yet dispatched when you call this
873
- * method. For example, suppose action `StartAction` starts a process that takes some time
874
- * to run and then dispatches an action called `MyFinalAction`. You can then write:
875
- *
876
- * ```dart
877
- * dispatch(StartAction());
878
- * let action = await store.waitAnyActionTypeFinishes([MyFinalAction]);
879
- * expect(action.status.originalError).toBeInstanceOf(UserException>);
880
- * ```
881
- *
882
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
883
- * To disable the timeout, make it 0 or -1.
884
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
885
- *
886
- * Examples:
887
- *
888
- * ```ts
889
- * // Dispatches an actions that changes the state, then await for the state change:
890
- * expect(store.state.name).toBe('John');
891
- * dispatch(new ChangeNameAction("Bill"));
892
- * let action = await store.waitCondition((state) => state.name == "Bill");
893
- * expect(action instanceof ChangeNameAction).toBe(true);
894
- * expect(store.state.name).toBe('Bill');
895
- *
896
- * // Dispatches actions and wait until no actions are in progress.
897
- * dispatch(new BuyAction('IBM'));
898
- * dispatch(new BuyAction('TSLA'));
899
- * await waitAllActions();
900
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
901
- *
902
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
903
- * expect(store.state.portfolio).toEqual(['TSLA']);
904
- * dispatch(new BuyAction('IBM'));
905
- * dispatch(new SellAction('TSLA'));
906
- * await store.waitAllActionTypes([BuyAction, SellAction]);
907
- * expect(store.state.portfolio).toEqual(['IBM']);
908
- *
909
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
910
- * dispatch(new BuyAction('IBM'));
911
- * dispatch(new BuyAction('TSLA'));
912
- * await store.waitAllActions();
913
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
914
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
915
- *
916
- * // Dispatches two actions in PARALLEL and wait for them:
917
- * let action1 = new BuyAction('IBM');
918
- * let action2 = new SellAction('TSLA');
919
- * dispatch(action1);
920
- * dispatch(action2);
921
- * await store.waitAllActions([action1, action2]);
922
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
923
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
924
- *
925
- * // Dispatches two actions in SERIES and wait for them:
926
- * await dispatchAndWait(new BuyAction('IBM'));
927
- * await dispatchAndWait(new SellAction('TSLA'));
928
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
929
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
930
- *
931
- * // Wait until some action of a given type is dispatched.
932
- * dispatch(new DoALotOfStuffAction());
933
- * let action = await store.waitActionType(ChangeNameAction);
934
- * expect(action instanceof ChangeNameAction).toBe(true);
935
- * expect(action.status.isCompletedOk).toBe(true);
936
- * expect(store.state.name).toBe('Bill');
937
- *
938
- * // Wait until some action of the given types is dispatched.
939
- * dispatch(new ProcessStocksAction());
940
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
941
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
942
- * ```
943
- *
944
- * See also:
945
- * `waitCondition` - Waits until the state is in a given condition.
946
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
947
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
948
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
949
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
950
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
951
- *
952
- * You should only use this method in tests.
953
- */
954
- async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null } = {}) {
955
- return this.store.waitAnyActionTypeFinishes(actionTypes, {
956
- timeoutMillis: timeoutMillis
957
- });
958
- }
959
- }
960
- class RefState {
961
- constructor(selectorAndValueAndSetValue) {
962
- this.selectorAndValueAndSetValue = selectorAndValueAndSetValue;
963
- }
964
- }
965
- class RefStore {
966
- constructor(selectorAndValueAndSetValue) {
967
- this.selectorAndValueAndSetValue = selectorAndValueAndSetValue;
968
- }
969
- }
1
+ "use strict";
2
+ 'use client';
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useSelect = useSelect;
5
+ exports.useSelector = useSelector;
6
+ exports.useObject = useObject;
7
+ exports.useAllState = useAllState;
8
+ exports.useStore = useStore;
9
+ exports.useDispatcher = useDispatcher;
10
+ exports.useDispatch = useDispatch;
11
+ exports.useStoreEffect = useStoreEffect;
12
+ exports.useDispatchAndWait = useDispatchAndWait;
13
+ exports.useDispatchAndWaitAll = useDispatchAndWaitAll;
14
+ exports.useDispatchWhen = useDispatchWhen;
15
+ exports.useDispatchAll = useDispatchAll;
16
+ exports.useDispatchSync = useDispatchSync;
17
+ exports.useIsWaiting = useIsWaiting;
18
+ exports.useIsStoreReady = useIsStoreReady;
19
+ exports.useIsFocused = useIsFocused;
20
+ exports.useIsOnline = useIsOnline;
21
+ exports.useEnvironment = useEnvironment;
22
+ exports.useConfiguration = useConfiguration;
23
+ exports.useIsFailed = useIsFailed;
24
+ exports.useExceptionFor = useExceptionFor;
25
+ exports.useClearExceptionFor = useClearExceptionFor;
26
+ exports.useSuspense = useSuspense;
27
+ exports.useEvent = useEvent;
28
+ exports.useLayoutEvent = useLayoutEvent;
29
+ const react_1 = require("react");
30
+ const with_selector_1 = require("use-sync-external-store/with-selector");
31
+ const StoreException_1 = require("./StoreException");
32
+ const StoreProvider_1 = require("./StoreProvider");
33
+ const Evt_1 = require("./Evt");
34
+ // How the hooks connect to the store
35
+ //
36
+ // The hooks that read the store use React's `useSyncExternalStore`, which gets two functions
37
+ // from the store: one to subscribe to changes, and one to read the current value (the
38
+ // "snapshot"). The store only tells React that something may have changed; React then reads the
39
+ // snapshot again, compares it with the one it rendered, and renders the component only if it
40
+ // changed. React also reads the snapshot again before committing a render that it started and
41
+ // paused (a transition), and restarts the render if the store changed meanwhile, so a screen
42
+ // never shows parts of two different states at the same time.
43
+ //
44
+ // - `useSelect`, `useObject` and `useAllState` use the React team's `useSyncExternalStoreWithSelector`,
45
+ // whose snapshot is the whole (immutable) state, and whose selector picks a part of it. It
46
+ // keeps the last selected value, and compares the new one with it (`Object.is` for `useSelect`,
47
+ // value by value for `useObject`), so an unchanged selection doesn't render the component.
48
+ //
49
+ // - `useIsWaiting`, `useIsFailed` and `useExceptionFor` read a boolean or an exception from the
50
+ // store, and subscribe to the status changes of the actions. `useIsStoreReady` reads a boolean
51
+ // and subscribes to the readiness. `useSuspense` reads, with the same subscription, a stable
52
+ // promise (while the action runs) or the failure, and throws it.
53
+ //
54
+ // What this means for your selectors: they must be pure, and must not depend on how many times
55
+ // they are called. React may call them more than once per render, and may throw a render away.
56
+ // Store-driven renders are synchronous for React (even inside `startTransition`): they are not
57
+ // deferred like local-state transitions. Async actions are still async; this only says how React
58
+ // schedules the render after the state changes.
59
+ /**
60
+ * Returns a part of the store state:
61
+ *
62
+ * ```ts
63
+ * const name = useSelect((state: State) => state.user.name);
64
+ * ```
65
+ *
66
+ * The component will rebuild only when the `name` changes, ignoring the
67
+ * change in other parts of the state. The selected value is compared with
68
+ * the previous one using `Object.is`, like React does. So `NaN` is equal
69
+ * to `NaN`, but `0` is different from `-0`.
70
+ *
71
+ * The selector must be pure: it must only read its `state` parameter, and return the same
72
+ * value for the same state. It may be an inline function, and may use props and local state.
73
+ * It should return a part of the state, not a new object: a new object is never `Object.is`
74
+ * the previous one, so the component would rebuild for every state change. Use `useObject`
75
+ * for that.
76
+ *
77
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
78
+ * Prefer `useSelect` because it's shorter.
79
+ */
80
+ function useSelect(selector) {
81
+ const { store, getServerState } = useStoreContext();
82
+ return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState, store._getState, getServerState, selector, Object.is);
83
+ }
84
+ /**
85
+ * Returns a part of the store state:
86
+ *
87
+ * ```ts
88
+ * const name = useSelector((state: State) => state.user.name);
89
+ * ```
90
+ *
91
+ * The component will rebuild only when the `name` changes, ignoring the
92
+ * change in other parts of the state.
93
+ *
94
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
95
+ * Prefer `useSelect` because it's shorter.
96
+ */
97
+ function useSelector(selector) {
98
+ return useSelect(selector);
99
+ }
100
+ /**
101
+ * Returns an object (or an array, `Map` or `Set`) with some parts of the store state:
102
+ *
103
+ * ```ts
104
+ * const user = useObject((state: State) => ({ name: state.user.name, age: state.user.age }));
105
+ * return <div>{user.name} is {user.age} years old</div>;
106
+ * ```
107
+ *
108
+ * The component will rebuild only when the `name` or the `age` changes, ignoring the
109
+ * change in other parts of the state.
110
+ *
111
+ * Note: With `useSelect`, the same selector would rebuild the component for ALL state changes,
112
+ * since it creates a new object each time. Instead, `useObject` compares the new object with
113
+ * the previous one, value by value (with `Object.is`). If they have the same values, it
114
+ * returns the previous object, and the component doesn't rebuild. This also works if the
115
+ * selector returns an array: `useObject((state: State) => [state.name, state.age])`, or a
116
+ * `Map` or a `Set`, whose entries are compared in order.
117
+ *
118
+ * Note the values themselves are compared by identity. So, the selector should return parts
119
+ * of the state, and not create new objects or arrays for its values.
120
+ *
121
+ * Only plain objects, arrays, `Map`s and `Set`s are compared value by value. Anything else,
122
+ * like a `Date`, a class instance, or a subclass of `Map` or `Set`, is compared by identity,
123
+ * like `useSelect` does. So, `useObject((state: State) => new Point(state.x, state.y))` would
124
+ * rebuild the component for ALL state changes.
125
+ *
126
+ * For this reason, the selector's type only accepts a plain object, an array, a `Map` or a
127
+ * `Set` (or `null` or `undefined`), and a class instance, a `Date`, a string, a number or a
128
+ * function doesn't compile. Note an object whose type is an `interface` doesn't compile either,
129
+ * since TypeScript can't tell it apart from a class instance. Declare it with `type` instead.
130
+ *
131
+ * While the values are the same, `useObject` keeps returning the object it returned before,
132
+ * so you can use it in the dependencies of an effect, or pass it to a memoized component.
133
+ */
134
+ function useObject(selector) {
135
+ const { store, getServerState } = useStoreContext();
136
+ return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState, store._getState, getServerState, selector, _shallowEqual);
137
+ }
138
+ // Returns true if `a` and `b` are the same, or are both plain objects, arrays, `Map`s or `Set`s
139
+ // with the same values (compared with `Object.is`). The entries of a `Map` or `Set` must also be
140
+ // in the same order, since that's the order they are rendered in. Other objects, like a `Date`,
141
+ // a class instance, or a subclass of `Map` or `Set`, are only equal if they are the same object,
142
+ // since their values may not be in their own enumerable keys.
143
+ function _shallowEqual(a, b) {
144
+ if (Object.is(a, b))
145
+ return true;
146
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
147
+ return false;
148
+ if (Array.isArray(a) || Array.isArray(b)) {
149
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
150
+ return false;
151
+ for (let i = 0; i < a.length; i++)
152
+ if (!Object.is(a[i], b[i]))
153
+ return false;
154
+ return true;
155
+ }
156
+ const proto = Object.getPrototypeOf(a);
157
+ if (proto !== Object.getPrototypeOf(b))
158
+ return false;
159
+ if (proto === Map.prototype) {
160
+ const mapA = a, mapB = b;
161
+ if (mapA.size !== mapB.size)
162
+ return false;
163
+ const entriesB = mapB.entries();
164
+ for (const [key, value] of mapA) {
165
+ const [keyB, valueB] = entriesB.next().value;
166
+ if (!Object.is(key, keyB) || !Object.is(value, valueB))
167
+ return false;
168
+ }
169
+ return true;
170
+ }
171
+ if (proto === Set.prototype) {
172
+ const setA = a, setB = b;
173
+ if (setA.size !== setB.size)
174
+ return false;
175
+ const valuesB = setB.values();
176
+ for (const value of setA)
177
+ if (!Object.is(value, valuesB.next().value))
178
+ return false;
179
+ return true;
180
+ }
181
+ if (proto !== Object.prototype && proto !== null)
182
+ return false;
183
+ const keysA = Object.keys(a);
184
+ const keysB = Object.keys(b);
185
+ if (keysA.length !== keysB.length)
186
+ return false;
187
+ for (const key of keysA) {
188
+ if (!Object.prototype.hasOwnProperty.call(b, key))
189
+ return false;
190
+ if (!Object.is(a[key], b[key]))
191
+ return false;
192
+ }
193
+ return true;
194
+ }
195
+ /**
196
+ * Returns the whole store state:
197
+ *
198
+ * ```ts
199
+ * const state = useAllState<State>();
200
+ * const name = state.user.name;
201
+ * ```
202
+ *
203
+ * While that's convenient, the above code will rebuild the component for all state changes,
204
+ * no matter if the name changed or not. For this reason, prefer `useSelector`:
205
+ *
206
+ * ```ts
207
+ * const name = useSelector((state: State) => state.user.name);
208
+ * ```
209
+ *
210
+ * Now it will rebuild only when the name changes.
211
+ */
212
+ function useAllState() {
213
+ return useSelect((state) => state);
214
+ }
215
+ /**
216
+ * Returns an object with all the dispatch and wait methods of the store:
217
+ *
218
+ * - `dispatch` - Dispatches an action, to potentially change the state.
219
+ * - `dispatchAndWait` - Dispatches an action and returns a promise that resolves when the action finishes.
220
+ * - `dispatchSync` - Same as the regular dispatch, except it throws an error if the action is ASYNC.
221
+ * - `dispatchWhen` - Waits until the state is in a given condition, and then dispatches an action.
222
+ * - `dispatchAll` - Dispatches all given actions in parallel.
223
+ * - `dispatchAndWaitAll` - Dispatches all given actions, and returns a promise that resolves when they all finish.
224
+ * - `waitCondition` - Waits until the state is in a given condition.
225
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
226
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
227
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
228
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
229
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
230
+ *
231
+ * Example:
232
+ *
233
+ * ```js
234
+ * const store = useStore();
235
+ * store.dispatch(new MyAction());
236
+ * await store.dispatchAndWait(new MyAction());
237
+ * store.dispatchSync(new MyAction());
238
+ * store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
239
+ * await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
240
+ * await store.waitCondition((state) => state.user.name === "Bill", { timeoutMillis: 1000 });
241
+ * await store.waitAllActionTypes([BuyAction, SellAction]);
242
+ * ```
243
+ *
244
+ * The methods also work when destructured: `const { dispatch, dispatchAndWait } = useStore();`.
245
+ *
246
+ * The object also has `store`, which is the store itself, with its `state` and all its other
247
+ * methods:
248
+ *
249
+ * ```js
250
+ * const { store } = useStore();
251
+ * console.log(store.actionsInProgress());
252
+ * ```
253
+ *
254
+ * IMPORTANT: `useStore` doesn't make the component re-render when the state changes. So, read
255
+ * `store.state` only in event handlers, effects and callbacks, never to render the component.
256
+ * To render it, use the hooks that re-render the component when needed:
257
+ * - To get the state: `useSelect`, `useObject` or `useAllState`
258
+ * - To know if actions are running: `useIsWaiting`
259
+ * - To deal with exceptions: `useIsFailed`, `useExceptionFor` and `useClearExceptionFor`
260
+ * - To use `<Suspense>` and error boundaries instead: `useSuspense`
261
+ *
262
+ * See also:
263
+ * - `useDispatch()` - Hook equivalent to `useStore().dispatch`
264
+ * - `useDispatchAndWait` - Hook equivalent to `useStore().dispatchAndWait`
265
+ * - `useDispatchSync` - Hook equivalent to `useStore().dispatchSync`
266
+ * - `useDispatchWhen` - Hook equivalent to `useStore().dispatchWhen`
267
+ * - `useDispatchAll` - Hook equivalent to `useStore().dispatchAll`
268
+ * - `useDispatchAndWaitAll` - Hook equivalent to `useStore().dispatchAndWaitAll`
269
+ * - `useStoreEffect` - To dispatch actions when the component mounts, when some values change,
270
+ * and when it unmounts.
271
+ */
272
+ function useStore() {
273
+ const store = useStoreFromContext();
274
+ return (0, react_1.useMemo)(() => new StoreDispatchers(store), [store]);
275
+ }
276
+ /**
277
+ * @deprecated Use `useDispatch`. Note you also have `useDispatchAndWait` and `useDispatchSync`.
278
+ */
279
+ function useDispatcher() {
280
+ return useDispatch();
281
+ }
282
+ /**
283
+ * Returns a function that dispatches an action, to potentially change the state:
284
+ *
285
+ * ```ts
286
+ * const dispatch = useDispatch();
287
+ * dispatch(new MyAction());
288
+ * ```
289
+ *
290
+ * This also works:
291
+ *
292
+ * ```ts
293
+ * const store = useStore();
294
+ * store.dispatch(new MyAction());
295
+ * ```
296
+ *
297
+ * To dispatch actions when the component mounts, when some values change, and when it
298
+ * unmounts, see `useStoreEffect`.
299
+ *
300
+ * See also:
301
+ * - `dispatchAll` which dispatches all given actions in parallel.
302
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
303
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
304
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
305
+ */
306
+ function useDispatch() {
307
+ const store = useStoreFromContext();
308
+ return (0, react_1.useMemo)(() => store.dispatch.bind(store), [store]);
309
+ }
310
+ /**
311
+ * Use `useStoreEffect` instead of a `useEffect` to dispatch actions when the component mounts
312
+ * (`onMount`), when some values change (`deps` and `onDepsChange`), and when it unmounts
313
+ * (`onUnmount`):
314
+ *
315
+ * ```tsx
316
+ * useStoreEffect({
317
+ * deps: userId,
318
+ * onMount: (store) => store.dispatch(new LoadUser(userId)),
319
+ * onDepsChange: (store, oldUserId) => {
320
+ * store.dispatch(new StopListening(oldUserId));
321
+ * store.dispatch(new LoadUser(userId));
322
+ * },
323
+ * onUnmount: (store) => store.dispatch(new CleanResources()),
324
+ * });
325
+ * ```
326
+ *
327
+ * If `deps` is an array, `onDepsChange` gets the old array:
328
+ *
329
+ * ```tsx
330
+ * useStoreEffect({
331
+ * deps: [userId, filter],
332
+ * onMount: (store) => store.dispatch(new LoadUser(userId, filter)),
333
+ * onDepsChange: (store, [oldUserId, oldFilter]) => {
334
+ * if (userId !== oldUserId) {
335
+ * store.dispatch(new StopListening(oldUserId));
336
+ * store.dispatch(new LoadUser(userId, filter));
337
+ * }
338
+ * else if (filter !== oldFilter) store.dispatch(new ApplyFilter(filter));
339
+ * },
340
+ * });
341
+ * ```
342
+ *
343
+ * All of them are optional, and get the store, so you can use any of its dispatch methods,
344
+ * and read its current `state`. They may be async. To type the state, type the store:
345
+ * `onMount: (store: Store<State>) => ...`. The hook returns nothing. To also dispatch actions
346
+ * from event handlers, use `useDispatch`, `useStore`, etc.
347
+ *
348
+ * Note you can still dispatch actions from a `useEffect`, as usual, if you prefer.
349
+ * `useStoreEffect` is just more convenient, because:
350
+ *
351
+ * - They only run after the store is ready (see `useIsStoreReady`). If the store is not ready
352
+ * when the component mounts, `onMount` is called as soon as it is. If the component unmounts
353
+ * before that, none of them is called.
354
+ *
355
+ * - They are called in order: `onMount`, then `onDepsChange` (any number of times), then
356
+ * `onUnmount`. But if one of them is async, it's not awaited (see below).
357
+ * `onMount` and `onUnmount` run once, even in React's `StrictMode`, which mounts components
358
+ * twice during development. And `onDepsChange` runs once per change.
359
+ *
360
+ * - Like a `useEffect` cleanup, `onUnmount` runs when the component unmounts, before the
361
+ * `onMount` of a component mounted in the same render (in a route switch, for example).
362
+ *
363
+ * When they run, compared to a `useEffect` (in production and in development):
364
+ *
365
+ * - `onMount` runs at the same time as a `useEffect(..., [])` called in the same place of the
366
+ * component, if the store is ready. If not, it runs when the store becomes ready.
367
+ *
368
+ * - `onDepsChange` runs at the same time as a `useEffect(..., [deps])`, but not after the first
369
+ * render. The deps are compared like React does: each value with `Object.is`.
370
+ *
371
+ * - `onUnmount` runs at the same time as the cleanup of a `useEffect`, with one exception:
372
+ * if the component unmounts in the same synchronous run as its mount (before any microtask),
373
+ * `onUnmount` waits one microtask. This is when `StrictMode` does its fake unmount, so if the
374
+ * component mounts again in that time, `onUnmount` is cancelled, and `onMount` is not called
375
+ * again. A real unmount that soon is rare, but its `onUnmount` also runs one microtask later.
376
+ *
377
+ * - So the actions they dispatch are dispatched at the same time as from a `useEffect`. A sync
378
+ * action changes the state before `onMount`, `onDepsChange` or `onUnmount` returns.
379
+ *
380
+ * - They are not awaited. If one of them is async, the next one may run before it finishes.
381
+ * For example, `onUnmount` may run while an async `onMount` is still waiting for an action.
382
+ *
383
+ * - Their errors are not caught, as in a `useEffect`. A sync error goes to React, which shows
384
+ * the nearest error boundary (except that React 18 doesn't give an error thrown by
385
+ * `onUnmount` while the component unmounts to the boundary: it logs it as an internal React
386
+ * error; React 19 fixed it). A rejected promise is an unhandled promise rejection. And when
387
+ * `onMount` waits for the store to be ready, or `onUnmount` waits a microtask (see above),
388
+ * even a sync error is an unhandled promise rejection. If `onMount` throws a sync error when
389
+ * the component mounts (the store is ready), `onUnmount` is not called, as the cleanup of a
390
+ * `useEffect` whose setup throws.
391
+ *
392
+ * - They are the ones from the latest render, so they see its values.
393
+ *
394
+ * - Some React features disconnect the effects and connect them again, without a real unmount.
395
+ * As for a `useEffect`, this calls `onUnmount` and then `onMount` again. For example, in
396
+ * development, Fast Refresh does it to a component when you edit its code. And `<Activity>`
397
+ * does it when it hides the component and shows it again.
398
+ *
399
+ * - A component can call `useStoreEffect` more than once. They run in the order they are called.
400
+ *
401
+ * Note: Changing `deps` doesn't call `onMount` again. If you want to dispatch the same actions
402
+ * on mount and when `deps` change, call the same function from both `onMount` and
403
+ * `onDepsChange`. Each of them sees the values from the latest render.
404
+ *
405
+ * To reload the data on screen when the user comes back to the tab, or when the internet comes
406
+ * back, use `onFocus` and `onOnline` (and `onBlur` and `onOffline` for the opposite):
407
+ *
408
+ * ```tsx
409
+ * useStoreEffect({
410
+ * onMount: (store) => store.dispatch(new LoadPrices()),
411
+ * onFocus: (store) => store.dispatch(new LoadPrices()),
412
+ * onOnline: (store) => store.dispatch(new LoadPrices()),
413
+ * });
414
+ * ```
415
+ *
416
+ * - They are called on the transitions only (hidden → visible, offline → online, and back),
417
+ * never on mount, and only while the component is mounted and after `onMount` was called
418
+ * (so, after the store is ready). Like the other callbacks, they get the store, see the
419
+ * values of the latest render, and are not awaited.
420
+ *
421
+ * - To only reload when the data is old, give the action a `fresh` period: a focus within the
422
+ * period is then aborted silently. Without `fresh`, the action runs on every focus.
423
+ *
424
+ * - What "focused" and "online" mean comes from the store: `store.isFocused` and
425
+ * `store.isOnline`, with `focusSource` and `onlineSource` in `createStore` to change the
426
+ * defaults (for example, in React Native). In tests, drive them with `store.setFocused()` and
427
+ * `store.setOnline()`.
428
+ *
429
+ * - A component that doesn't give these callbacks doesn't make the store listen to the focus
430
+ * and online sources.
431
+ */
432
+ function useStoreEffect(options) {
433
+ const store = useStoreFromContext();
434
+ // The options from the latest committed render, so that the callbacks see the latest values.
435
+ // A passive effect is enough: the effects below, which read the ref, run after it in the
436
+ // same commit (effects of a component run in order). A layout effect would also warn on the
437
+ // server with React 18 ("useLayoutEffect does nothing on the server").
438
+ const optionsRef = (0, react_1.useRef)(options);
439
+ (0, react_1.useEffect)(() => {
440
+ optionsRef.current = options;
441
+ });
442
+ // The store for which `onMount` was called, or null if it wasn't called (or after `onUnmount`).
443
+ const mountedStoreRef = (0, react_1.useRef)(null);
444
+ // The deps seen by the last `onMount` or `onDepsChange`.
445
+ const lastDepsRef = (0, react_1.useRef)(undefined);
446
+ // The `onUnmount` waiting to run. See below why it waits.
447
+ const pendingUnmountRef = (0, react_1.useRef)(null);
448
+ (0, react_1.useEffect)(() => {
449
+ // In `StrictMode`, React unmounts and then mounts again right away. This is not a real
450
+ // unmount, so we cancel the `onUnmount` that is waiting to run.
451
+ const pending = pendingUnmountRef.current;
452
+ if (pending !== null && pending.store === store) {
453
+ pending.isCancelled = true;
454
+ pendingUnmountRef.current = null;
455
+ }
456
+ let isActive = true;
457
+ // True until the end of the current synchronous flush. StrictMode's fake unmount happens
458
+ // right after the mount, in the same flush, so only an unmount in that time can be fake.
459
+ let isJustMounted = true;
460
+ Promise.resolve().then(() => isJustMounted = false);
461
+ if (mountedStoreRef.current !== store) {
462
+ const mount = () => {
463
+ if (!isActive)
464
+ return;
465
+ mountedStoreRef.current = store;
466
+ lastDepsRef.current = optionsRef.current?.deps;
467
+ optionsRef.current?.onMount?.(store);
468
+ };
469
+ if (store._isReady)
470
+ mount();
471
+ else
472
+ store.ready().then(mount);
473
+ }
474
+ return () => {
475
+ isActive = false;
476
+ if (mountedStoreRef.current !== store)
477
+ return;
478
+ const unmount = () => {
479
+ if (mountedStoreRef.current === store)
480
+ mountedStoreRef.current = null;
481
+ optionsRef.current?.onUnmount?.(store);
482
+ };
483
+ // A real unmount. Runs `onUnmount` right away, like a `useEffect` cleanup, so that it runs
484
+ // before the `onMount` of a component mounted in the same commit (a route switch, for example).
485
+ if (!isJustMounted) {
486
+ unmount();
487
+ return;
488
+ }
489
+ // It may be StrictMode's fake unmount. Waits a microtask, so that it can be cancelled if
490
+ // this is not a real unmount (see above).
491
+ const pendingUnmount = { store, isCancelled: false };
492
+ pendingUnmountRef.current = pendingUnmount;
493
+ Promise.resolve().then(() => {
494
+ if (pendingUnmount.isCancelled)
495
+ return;
496
+ if (pendingUnmountRef.current === pendingUnmount)
497
+ pendingUnmountRef.current = null;
498
+ unmount();
499
+ });
500
+ };
501
+ }, [store]);
502
+ // After each render, calls `onDepsChange` if the deps changed (only after `onMount` was called).
503
+ (0, react_1.useEffect)(() => {
504
+ if (mountedStoreRef.current !== store)
505
+ return;
506
+ const deps = optionsRef.current?.deps;
507
+ const oldDeps = lastDepsRef.current;
508
+ if (_depsAreEqual(oldDeps, deps))
509
+ return;
510
+ lastDepsRef.current = deps;
511
+ optionsRef.current?.onDepsChange?.(store, oldDeps);
512
+ });
513
+ // Listens to the focus and online signals of the store, only while some render gave one of
514
+ // their callbacks, so that a component with `onMount` only doesn't start the sources. The
515
+ // callbacks run on the transitions only, and only after `onMount` was called.
516
+ const listensToFocus = !!(options.onFocus || options.onBlur);
517
+ const listensToOnline = !!(options.onOnline || options.onOffline);
518
+ (0, react_1.useEffect)(() => {
519
+ if (!listensToFocus)
520
+ return;
521
+ return _listenToSignal(store._subscribeFocus, store._getIsFocused, (isFocused) => {
522
+ if (mountedStoreRef.current !== store)
523
+ return;
524
+ if (isFocused)
525
+ optionsRef.current?.onFocus?.(store);
526
+ else
527
+ optionsRef.current?.onBlur?.(store);
528
+ });
529
+ }, [store, listensToFocus]);
530
+ (0, react_1.useEffect)(() => {
531
+ if (!listensToOnline)
532
+ return;
533
+ return _listenToSignal(store._subscribeOnline, store._getIsOnline, (isOnline) => {
534
+ if (mountedStoreRef.current !== store)
535
+ return;
536
+ if (isOnline)
537
+ optionsRef.current?.onOnline?.(store);
538
+ else
539
+ optionsRef.current?.onOffline?.(store);
540
+ });
541
+ }, [store, listensToOnline]);
542
+ }
543
+ // Subscribes to a boolean signal of the store, and calls `onChange` each time it changes.
544
+ function _listenToSignal(subscribe, get, onChange) {
545
+ let last = get();
546
+ return subscribe(() => {
547
+ const value = get();
548
+ if (value === last)
549
+ return;
550
+ last = value;
551
+ onChange(value);
552
+ });
553
+ }
554
+ // Compares deps like React does: each value with `Object.is`.
555
+ function _depsAreEqual(a, b) {
556
+ if (Array.isArray(a) && Array.isArray(b)) {
557
+ if (a.length !== b.length)
558
+ return false;
559
+ for (let i = 0; i < a.length; i++)
560
+ if (!Object.is(a[i], b[i]))
561
+ return false;
562
+ return true;
563
+ }
564
+ return Object.is(a, b);
565
+ }
566
+ /**
567
+ * Dispatches an action and returns a promise that resolves when the action finishes.
568
+ * While the state change from the action's reducer will have been applied when the promise
569
+ * resolves, other independent processes that the action may have started may still be in
570
+ * progress.
571
+ *
572
+ * Usage:
573
+ * ```ts
574
+ * const dispatchAndWait = useDispatchAndWait();
575
+ * await dispatchAndWait(new MyAction());
576
+ * ```
577
+ *
578
+ * See also:
579
+ * - `dispatch` which dispatches both sync and async actions.
580
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
581
+ * - `dispatchAll` which dispatches all given actions in parallel.
582
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
583
+ */
584
+ function useDispatchAndWait() {
585
+ const store = useStoreFromContext();
586
+ return (0, react_1.useMemo)(() => store.dispatchAndWait.bind(store), [store]);
587
+ }
588
+ /**
589
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
590
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
591
+ * ALL actions finish.
592
+ *
593
+ * ```ts
594
+ * const dispatchAndWaitAll = useDispatchAndWaitAll();
595
+ * await dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
596
+ * ```
597
+ *
598
+ * Note: While the state change from the action's reducers will have been applied when the
599
+ * Promise resolves, other independent processes that the action may have started may still
600
+ * be in progress.
601
+ *
602
+ * See also:
603
+ * - `dispatch` which dispatches both sync and async actions.
604
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
605
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
606
+ * - `dispatchAll` which dispatches all given actions in parallel.
607
+ */
608
+ function useDispatchAndWaitAll() {
609
+ const store = useStoreFromContext();
610
+ return (0, react_1.useMemo)(() => store.dispatchAndWaitAll.bind(store), [store]);
611
+ }
612
+ /**
613
+ * Waits until the store state meets a certain condition, and then dispatches an action.
614
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
615
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
616
+ * the condition, so no other action can change the state in between.
617
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
618
+ * dispatched one after the other, and each condition is checked again right before its
619
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
620
+ *
621
+ * ```ts
622
+ * const dispatchWhen = useDispatchWhen();
623
+ * dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
624
+ * ```
625
+ *
626
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
627
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
628
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
629
+ * timeout is logged. To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`),
630
+ * but note that while it waits, the condition runs on every state change.
631
+ *
632
+ * ```ts
633
+ * dispatchWhen(
634
+ * new BuyStock('IBM'),
635
+ * (state) => state.stocks.getPrice('IBM') >= 100,
636
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
637
+ * );
638
+ * ```
639
+ *
640
+ * Note: The wait is NOT cancelled when the component unmounts.
641
+ *
642
+ * See also:
643
+ * - `dispatch` which dispatches both sync and async actions.
644
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
645
+ */
646
+ function useDispatchWhen() {
647
+ const store = useStoreFromContext();
648
+ return (0, react_1.useMemo)(() => store.dispatchWhen.bind(store), [store]);
649
+ }
650
+ /**
651
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
652
+ * the store state.
653
+ *
654
+ * ```ts
655
+ * const dispatchAll = useDispatchAll();
656
+ * dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
657
+ * ```
658
+ *
659
+ * See also:
660
+ * - `dispatch` which dispatches both sync and async actions.
661
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
662
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
663
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
664
+ */
665
+ function useDispatchAll() {
666
+ const store = useStoreFromContext();
667
+ return (0, react_1.useMemo)(() => store.dispatchAll.bind(store), [store]);
668
+ }
669
+ /**
670
+ * Dispatches the given action to the Redux store, to potentially change the state.
671
+ *
672
+ * This is exactly the same as the regular `dispatch`, except for the fact it
673
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
674
+ * if any of its `reduce()` or `before()` methods return a Promise.
675
+ *
676
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
677
+ * action is SYNC, which means the state gets changed right after the dispatch call.
678
+ *
679
+ * See also:
680
+ * - `dispatch` which dispatches both sync and async actions.
681
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
682
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
683
+ * - `dispatchAll` which dispatches all given actions in parallel.
684
+ */
685
+ function useDispatchSync() {
686
+ const store = useStoreFromContext();
687
+ return (0, react_1.useMemo)(() => store.dispatchSync.bind(store), [store]);
688
+ }
689
+ /**
690
+ * You can use `isWaiting` and pass it an action `type`:
691
+ * - It returns true if an action of the given type (or of a subclass) is currently being processed.
692
+ * - It returns false if no action of the given type is currently being processed.
693
+ * - This is only useful for ASYNC actions. A SYNC action finishes before `dispatch` returns, so
694
+ * outside of it, `isWaiting` is always `false` for it, and components never see it as `true`.
695
+ *
696
+ * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
697
+ *
698
+ * ```ts
699
+ * const isWaiting = useIsWaiting(MyAction);
700
+ * if (isWaiting) { ... } // Show a spinner
701
+ * ```
702
+ *
703
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
704
+ * `KissAction.statusKey`): `useIsWaiting(LoadUser, { statusKey: userId })`.
705
+ */
706
+ function useIsWaiting(type, options) {
707
+ const store = useStoreFromContext();
708
+ const statusKey = options?.statusKey;
709
+ const getIsWaiting = (0, react_1.useCallback)(() => store.isWaiting(type, { statusKey }), [store, type, statusKey]);
710
+ return (0, react_1.useSyncExternalStore)(store._subscribeStatus, getIsWaiting, _returnFalse);
711
+ }
712
+ // On the server and while hydrating, no action is waiting or failed, and the store is ready.
713
+ // See `StoreProviderProps.serverState`.
714
+ const _returnFalse = () => false;
715
+ const _returnNull = () => null;
716
+ const _returnTrue = () => true;
717
+ /**
718
+ * Returns true if the store is ready, and false while it's still loading the persisted state.
719
+ * See `Store.ready()`.
720
+ *
721
+ * You can show the UI before the store is ready, using the initial-state. But dispatching an
722
+ * action before the store is ready throws a `StoreException`. Use this hook to show a loading
723
+ * state, and to disable the buttons that dispatch actions:
724
+ *
725
+ * ```tsx
726
+ * const isReady = useIsStoreReady();
727
+ * if (!isReady) return <Spinner/>;
728
+ * // or: <button disabled={!isReady} onClick={() => dispatch(new AddTodo())}>Add</button>
729
+ * ```
730
+ *
731
+ * A store without a persistor is always ready. Once ready, a store stays ready.
732
+ */
733
+ function useIsStoreReady() {
734
+ const store = useStoreFromContext();
735
+ return (0, react_1.useSyncExternalStore)(store._subscribeReady, store._getIsReady, _returnTrue);
736
+ }
737
+ /**
738
+ * Returns true if the app is focused (in the browser, if the document is visible: the user is
739
+ * on the tab that shows the app). See `store.isFocused`. The component re-renders when it
740
+ * changes. On the server, it's always `true`.
741
+ *
742
+ * To dispatch an action when the app is focused again, use `useStoreEffect` with `onFocus`.
743
+ */
744
+ function useIsFocused() {
745
+ const store = useStoreFromContext();
746
+ return (0, react_1.useSyncExternalStore)(store._subscribeFocus, store._getIsFocused, _returnTrue);
747
+ }
748
+ /**
749
+ * Returns true if the app is online. See `store.isOnline`. The component re-renders when it
750
+ * changes, so you can show an "offline" banner. On the server, it's always `true`.
751
+ *
752
+ * ```tsx
753
+ * const isOnline = useIsOnline();
754
+ * if (!isOnline) return <Banner>You are offline</Banner>;
755
+ * ```
756
+ *
757
+ * To dispatch an action when the internet comes back, use `useStoreEffect` with `onOnline`.
758
+ */
759
+ function useIsOnline() {
760
+ const store = useStoreFromContext();
761
+ return (0, react_1.useSyncExternalStore)(store._subscribeOnline, store._getIsOnline, _returnTrue);
762
+ }
763
+ /**
764
+ * Returns the environment of the store (production, staging, testing, etc), given to
765
+ * `createStore` as `environment`, or `undefined`. For example, to show a debug banner:
766
+ *
767
+ * ```ts
768
+ * const env = useEnvironment<Environment>();
769
+ * if (env !== Environment.production) return <DebugBanner />;
770
+ * ```
771
+ *
772
+ * Give it the type of the environment, as above. It never re-renders the component, since
773
+ * the environment doesn't change while the app runs.
774
+ *
775
+ * See also: `useConfiguration`. There is no hook for the dependencies, since components
776
+ * should usually not need them. In actions, read them with `this.store.environment`,
777
+ * `this.store.configuration` and `this.store.dependencies`.
778
+ */
779
+ function useEnvironment() {
780
+ return useStoreFromContext().environment;
781
+ }
782
+ /**
783
+ * Returns the configuration of the store (feature flags and other configuration values),
784
+ * created by the `configuration` factory given to `createStore`, or `undefined`. For
785
+ * example, to hide a feature behind a flag:
786
+ *
787
+ * ```ts
788
+ * const config = useConfiguration<Config>();
789
+ * if (config.showAdminConsole) return <AdminConsole />;
790
+ * ```
791
+ *
792
+ * Give it the type of the configuration, as above. It never re-renders the component, since
793
+ * the configuration doesn't change while the app runs.
794
+ *
795
+ * See also: `useEnvironment`.
796
+ */
797
+ function useConfiguration() {
798
+ return useStoreFromContext().configuration;
799
+ }
800
+ /**
801
+ * Returns true if the given action `type` failed, with any error, not only with a
802
+ * `UserException`. Use `exceptionFor` to get the error, if it was a `UserException`.
803
+ * An error swallowed by `wrapError` or the `errorObserver` (they returned `null`), and
804
+ * an `AbortDispatchException`, don't count as failures.
805
+ * Note: This method uses the EXACT action type. Subtypes are not considered.
806
+ *
807
+ * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
808
+ * `KissAction.statusKey`): `useIsFailed(LoadUser, { statusKey: userId })`.
809
+ */
810
+ function useIsFailed(type, options) {
811
+ const store = useStoreFromContext();
812
+ const statusKey = options?.statusKey;
813
+ const getIsFailed = (0, react_1.useCallback)(() => store.isFailed(type, { statusKey }), [store, type, statusKey]);
814
+ return (0, react_1.useSyncExternalStore)(store._subscribeStatus, getIsFailed, _returnFalse);
815
+ }
816
+ /**
817
+ * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
818
+ * or if it failed with an error that is not a `UserException` (in that case, `isFailed` is
819
+ * still true).
820
+ * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
821
+ *
822
+ * The exception is the object the action threw (or the one `wrapError` or the `errorObserver`
823
+ * returned). It's returned as is: don't change it after throwing it, since React compares it
824
+ * by identity to know if the component must rebuild.
825
+ *
826
+ * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
827
+ * `KissAction.statusKey`): `useExceptionFor(LoadUser, { statusKey: userId })`. Without it,
828
+ * if actions with different keys failed, you get the `UserException` of the most recent
829
+ * failure.
830
+ */
831
+ function useExceptionFor(type, options) {
832
+ const store = useStoreFromContext();
833
+ const statusKey = options?.statusKey;
834
+ const getExceptionFor = (0, react_1.useCallback)(() => store.exceptionFor(type, { statusKey }), [store, type, statusKey]);
835
+ return (0, react_1.useSyncExternalStore)(store._subscribeStatus, getExceptionFor, _returnNull);
836
+ }
837
+ /**
838
+ * Removes the exact given action `type` from the list of action types that failed.
839
+ * Note it clears the EXACT given type. Subtypes are not considered.
840
+ *
841
+ * Even if you never call this method explicitly, just dispatching an action already clears that action type
842
+ * from the list of failing action types. But you can call this method explicitly if you want to clear the
843
+ * action type before it's used again.
844
+ *
845
+ * Usage:
846
+ * ```ts
847
+ * const clearExceptionFor = useClearExceptionFor();
848
+ * clearExceptionFor(MyAction);
849
+ * clearExceptionFor(AnotherAction);
850
+ * ```
851
+ *
852
+ * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
853
+ * `KissAction.statusKey`): `clearExceptionFor(LoadUser, { statusKey: userId })`. Without it,
854
+ * all the failures of the type are cleared, whatever their keys.
855
+ */
856
+ function useClearExceptionFor() {
857
+ const store = useStoreFromContext();
858
+ return (0, react_1.useMemo)(() => (type, options) => {
859
+ store.clearExceptionFor(type, options);
860
+ }, [store]);
861
+ }
862
+ /**
863
+ * Suspends the component while an action of the given `type` is in progress, and throws the
864
+ * error to the nearest error boundary if the action failed. It's the alternative to
865
+ * `useIsWaiting` and `useIsFailed` for apps that prefer React's `<Suspense>` and error
866
+ * boundaries, like TanStack Query's `useSuspenseQuery`:
867
+ *
868
+ * ```tsx
869
+ * function UserName({ userId }: { userId: string }) {
870
+ * useSuspense(LoadUser, { statusKey: userId });
871
+ * const user = useSelect((state: State) => state.users[userId]);
872
+ * return <p>{user.name}</p>;
873
+ * }
874
+ *
875
+ * function UserCard({ userId }: { userId: string }) {
876
+ * return (
877
+ * <ErrorBoundary fallback={<p>Loading failed.</p>}>
878
+ * <Suspense fallback={<Spinner />}>
879
+ * <UserName userId={userId} />
880
+ * </Suspense>
881
+ * </ErrorBoundary>
882
+ * );
883
+ * }
884
+ * ```
885
+ *
886
+ * - While an action of the type (or of a subclass, like `useIsWaiting`) is in progress, the
887
+ * hook throws a promise. React stops the render there (the code after the hook doesn't run),
888
+ * shows the `fallback` of the nearest `<Suspense>` above the component, and renders the
889
+ * component again when the action finishes. The promise is the same object on every render
890
+ * while the action runs, and resolves when it finishes.
891
+ * - Otherwise, if the last action of the exact type failed (like `useIsFailed`: with any
892
+ * error, not only a `UserException`), the hook throws that error. The nearest error boundary
893
+ * above the component catches it. The failure stays recorded in the store, like with
894
+ * `useIsFailed`: dispatching the action again clears it (and makes the component suspend),
895
+ * and so does `clearExceptionFor`. So a "retry" button in the boundary should dispatch the
896
+ * action again, and then reset the boundary. Pass `{ throwErrors: false }` to not throw, and
897
+ * use `useIsFailed` or `useExceptionFor` instead.
898
+ * - Otherwise, the hook returns, and the component renders normally.
899
+ *
900
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
901
+ * `KissAction.statusKey`): `useSuspense(LoadUser, { statusKey: userId })`. Without it, the
902
+ * component suspends while any action of the type runs, and throws its most recent failure.
903
+ *
904
+ * On the server and while hydrating, the hook never suspends or throws, like `useIsWaiting`
905
+ * and `useIsFailed` are `false` there (see `StoreProviderProps.serverState`). After hydration,
906
+ * it follows the live store.
907
+ *
908
+ * Note: a component that suspends on its first render is thrown away and rendered again from
909
+ * the start, so its local state (`useState`, `useRef`) is lost. A component that already
910
+ * rendered keeps its state while suspended. This is how React's Suspense works.
911
+ */
912
+ function useSuspense(type, options) {
913
+ const store = useStoreFromContext();
914
+ const statusKey = options?.statusKey;
915
+ const throwErrors = options?.throwErrors ?? true;
916
+ const getValue = (0, react_1.useCallback)(() => store._suspenseValue(type, statusKey, throwErrors), [store, type, statusKey, throwErrors]);
917
+ const value = (0, react_1.useSyncExternalStore)(store._subscribeStatus, getValue, _returnNull);
918
+ if (value === null)
919
+ return;
920
+ if (value instanceof Promise)
921
+ throw value;
922
+ throw value.error;
923
+ }
924
+ /**
925
+ * Handles an event (`Evt` or `EvtState`) from the state, by calling the `callback` with its
926
+ * value, once per event:
927
+ *
928
+ * ```tsx
929
+ * function Feed() {
930
+ * const listRef = useRef<HTMLDivElement>(null);
931
+ * const inputRef = useRef<HTMLInputElement>(null);
932
+ *
933
+ * useEvent((state: State) => state.scrollToTopEvt, () => listRef.current?.scrollTo({ top: 0 }));
934
+ * useEvent((state: State) => state.changeTextEvt, (text) => { inputRef.current!.value = text; });
935
+ * ...
936
+ * }
937
+ * ```
938
+ *
939
+ * Events are for an action to ask the UI to do something once, that is not a state change:
940
+ * scroll a list, clear or focus an input, open a dialog. See `Evt` for how actions create them.
941
+ *
942
+ * The `selector` returns one event from the state (or `null`/`undefined`, to handle nothing).
943
+ * The `callback` runs in an effect, after the render that shows the new state is committed, like
944
+ * a `useEffect` (use `useLayoutEvent` to run it before the browser paints, like a
945
+ * `useLayoutEffect`). It's always the callback of the latest render, so it sees the latest props.
946
+ *
947
+ * For an `Evt`, the callback is called once per event, and then the event is **spent**:
948
+ *
949
+ * - A new event while the component is mounted: fires once.
950
+ * - An event created before the component mounts: fires once, when it mounts.
951
+ * - The component remounts later: doesn't fire, since the event is spent.
952
+ * - Two components use the same event: only the first one fires. Create two events for that.
953
+ * - Unrelated re-renders: doesn't fire.
954
+ * - In React's `StrictMode`, which runs effects twice in development: fires once.
955
+ *
956
+ * For an `EvtState`, the callback is called when the state has a different `EvtState` than the
957
+ * last one the component saw. It fires in every mounted component that uses it, but not when the
958
+ * component mounts or remounts, so events that happen while it's not mounted are missed.
959
+ *
960
+ * The store keeps which events were spent (see `store.isEventSpent`), so the events and the state
961
+ * stay immutable. Nothing is spent during render: React may throw a render away, so a render
962
+ * can't spend the event. That's why there is no way to consume an event in render, only this hook.
963
+ */
964
+ function useEvent(selector, callback) {
965
+ const handle = useEventHandler(selector);
966
+ (0, react_1.useEffect)(() => handle(callback), [handle, callback]);
967
+ }
968
+ /**
969
+ * The same as `useEvent`, but the `callback` runs in a layout effect, before the browser paints
970
+ * (like a `useLayoutEffect`). Use it when the UI work would otherwise flicker: a scroll, a focus,
971
+ * a measurement. Like `useLayoutEffect`, it does nothing on the server, and React 18 warns about it
972
+ * there. Prefer `useEvent` when the timing doesn't matter.
973
+ */
974
+ function useLayoutEvent(selector, callback) {
975
+ const handle = useEventHandler(selector);
976
+ (0, react_1.useLayoutEffect)(() => handle(callback), [handle, callback]);
977
+ }
978
+ // The implementation of `useEvent` and `useLayoutEvent`. Returns a function that handles the
979
+ // selected event with the given callback, if it wasn't handled yet. The function changes when the
980
+ // event (or the store) changes, so the effects above run it again then. They also run it again
981
+ // when the callback changes (an inline callback changes in every render), which does nothing, as
982
+ // the event is already handled. So it's always the callback of the latest render that handles a
983
+ // new event. Running it twice does nothing, which is what `StrictMode` does with effects.
984
+ function useEventHandler(selector) {
985
+ const store = useStoreFromContext();
986
+ const evt = useSelect(selector);
987
+ // For `EvtState` only: the last event the component saw, starting with the one at mount, so
988
+ // that mounting doesn't fire.
989
+ const lastSeenRef = (0, react_1.useRef)(evt);
990
+ return (0, react_1.useCallback)((callback) => {
991
+ if (evt == null)
992
+ return;
993
+ if (evt instanceof Evt_1.EvtState) {
994
+ if (lastSeenRef.current === evt)
995
+ return;
996
+ lastSeenRef.current = evt;
997
+ if (evt._spentAtCreation)
998
+ return;
999
+ callback(evt.value);
1000
+ return;
1001
+ }
1002
+ if (store.isEventSpent(evt))
1003
+ return;
1004
+ store._spentEvents.add(evt);
1005
+ callback(evt.value);
1006
+ }, [evt, store]);
1007
+ }
1008
+ function useStoreContext() {
1009
+ const context = (0, react_1.useContext)(StoreProvider_1.StoreContext);
1010
+ if (!context?.store) {
1011
+ throw new StoreException_1.StoreException('useStore must be used within a StoreProvider');
1012
+ }
1013
+ return context;
1014
+ }
1015
+ function useStoreFromContext() {
1016
+ return useStoreContext().store;
1017
+ }
1018
+ /**
1019
+ * Helper class that allows us to write:
1020
+ *
1021
+ * ```js
1022
+ * const store = useStore();
1023
+ * store.dispatch(new MyAction());
1024
+ * store.dispatchSync(new MyAction());
1025
+ * await store.dispatchAndWait(new MyAction());
1026
+ * store.dispatchAll([new MyAction(), new OtherAction()]);
1027
+ * await store.dispatchAndWaitAll([new MyAction(), new OtherAction()]);
1028
+ * ```
1029
+ */
1030
+ class StoreDispatchers {
1031
+ constructor(store) {
1032
+ this.store = store;
1033
+ // Bind the methods, so that they also work when destructured: `const { dispatch } = useStore()`.
1034
+ this.dispatch = this.dispatch.bind(this);
1035
+ this.dispatchWhen = this.dispatchWhen.bind(this);
1036
+ this.dispatchAndWait = this.dispatchAndWait.bind(this);
1037
+ this.dispatchSync = this.dispatchSync.bind(this);
1038
+ this.dispatchAll = this.dispatchAll.bind(this);
1039
+ this.dispatchAndWaitAll = this.dispatchAndWaitAll.bind(this);
1040
+ this.waitCondition = this.waitCondition.bind(this);
1041
+ this.waitActionCondition = this.waitActionCondition.bind(this);
1042
+ this.waitAllActions = this.waitAllActions.bind(this);
1043
+ this.waitActionType = this.waitActionType.bind(this);
1044
+ this.waitAllActionTypes = this.waitAllActionTypes.bind(this);
1045
+ this.waitAnyActionTypeFinishes = this.waitAnyActionTypeFinishes.bind(this);
1046
+ this.abort = this.abort.bind(this);
1047
+ }
1048
+ /**
1049
+ * Aborts all the actions of the given `type` (or of a subclass) that are in progress. Each
1050
+ * one finishes silently: its `abortSignal` is aborted, its result is ignored, and so are its
1051
+ * errors. See `Store.abort`.
1052
+ *
1053
+ * ```tsx
1054
+ * const { abort } = useStore();
1055
+ * <button onClick={() => abort(UploadFile)}>Cancel</button>
1056
+ * ```
1057
+ *
1058
+ * Pass `{ statusKey }` to abort only the actions with that `statusKey`.
1059
+ */
1060
+ abort(type, options) {
1061
+ this.store.abort(type, options);
1062
+ }
1063
+ /**
1064
+ * Dispatches the action to the Redux store, to potentially change the state.
1065
+ */
1066
+ dispatch(action) {
1067
+ return this.store.dispatch(action);
1068
+ }
1069
+ /**
1070
+ * Waits until the store state meets a certain condition, and then dispatches an action.
1071
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
1072
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
1073
+ * the condition, so no other action can change the state in between.
1074
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
1075
+ * dispatched one after the other, and each condition is checked again right before its
1076
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
1077
+ *
1078
+ * ```ts
1079
+ * store.dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
1080
+ * ```
1081
+ *
1082
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
1083
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
1084
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
1085
+ * timeout is logged with `Store.log()`. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
1086
+ * (or -1, or `Infinity`), but note that while it waits, the condition runs on every state change.
1087
+ * A `logOut()` cancels the `dispatchWhen`s that are still waiting: their action is not
1088
+ * dispatched, and their `onTimeout` is not called.
1089
+ *
1090
+ * ```ts
1091
+ * store.dispatchWhen(
1092
+ * new BuyStock('IBM'),
1093
+ * (state) => state.stocks.getPrice('IBM') >= 100,
1094
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
1095
+ * );
1096
+ * ```
1097
+ */
1098
+ dispatchWhen(action, condition, options) {
1099
+ this.store.dispatchWhen(action, condition, options);
1100
+ }
1101
+ /**
1102
+ * Dispatches an action and returns a promise that resolves when the action finishes.
1103
+ * While the state change from the action's reducer will have been applied when the promise
1104
+ * resolves, other independent processes that the action may have started may still be in
1105
+ * progress.
1106
+ *
1107
+ * Usage: `await store.dispatchAndWait(new MyAction())`.
1108
+ */
1109
+ dispatchAndWait(action) {
1110
+ return this.store.dispatchAndWait(action);
1111
+ }
1112
+ /**
1113
+ * Dispatches the given action to the Redux store, to potentially change the state.
1114
+ *
1115
+ * This is exactly the same as the regular `dispatch`, except for the fact it
1116
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
1117
+ * if any of its `reduce()` or `before()` methods return a Promise.
1118
+ *
1119
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
1120
+ * action is SYNC, which means the state gets changed right after the dispatch call.
1121
+ */
1122
+ dispatchSync(action) {
1123
+ return this.store.dispatchSync(action);
1124
+ }
1125
+ /**
1126
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
1127
+ * the store state. It returns the same list of actions, so that you can instantiate them
1128
+ * inline, but still get a list of them.
1129
+ *
1130
+ * ```ts
1131
+ * let actions = store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1132
+ * ```
1133
+ *
1134
+ * See also:
1135
+ * - `dispatch` which dispatches both sync and async actions.
1136
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1137
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
1138
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1139
+ */
1140
+ dispatchAll(actions) {
1141
+ return this.store.dispatchAll(actions);
1142
+ }
1143
+ /**
1144
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
1145
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
1146
+ * ALL actions finish, with the same list of actions.
1147
+ *
1148
+ * ```ts
1149
+ * let actions = await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1150
+ * ```
1151
+ *
1152
+ * Note: While the state change from the action's reducers will have been applied when the
1153
+ * Promise resolves, other independent processes that the action may have started may still
1154
+ * be in progress.
1155
+ *
1156
+ * If some actions fail with an error that is not swallowed (see `dispatchAndWait`), all
1157
+ * actions are still dispatched and allowed to finish. Only then the Promise rejects, with
1158
+ * the error of the first failed action in the list.
1159
+ *
1160
+ * See also:
1161
+ * - `dispatch` which dispatches both sync and async actions.
1162
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1163
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1164
+ * - `dispatchAll` which dispatches all given actions in parallel.
1165
+ */
1166
+ dispatchAndWaitAll(actions) {
1167
+ return this.store.dispatchAndWaitAll(actions);
1168
+ }
1169
+ /**
1170
+ * Returns a promise which will resolve when the given state `condition` is true.
1171
+ * If the condition is already true when the method is called, the promise resolves immediately.
1172
+ *
1173
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
1174
+ * is not met in `timeoutMillis` milliseconds, the promise rejects with a `TimeoutException`,
1175
+ * and the condition stops being checked. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
1176
+ * (or -1, or `Infinity`):
1177
+ *
1178
+ * ```ts
1179
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 }); // 1 second.
1180
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 0 }); // No timeout.
1181
+ * ```
1182
+ *
1183
+ * To handle the timeout, you can catch the `TimeoutException`:
1184
+ *
1185
+ * ```ts
1186
+ * try { await store.waitCondition(condition, { timeoutMillis: 5000 }); }
1187
+ * catch (error) { if (error instanceof TimeoutException) { ... } else throw error; }
1188
+ * ```
1189
+ *
1190
+ * Or, you can pass an `onTimeout` callback. If the timeout expires, `onTimeout` is called,
1191
+ * and the promise resolves with `null` instead of rejecting. If `onTimeout` throws, the
1192
+ * promise rejects with that error:
1193
+ *
1194
+ * ```ts
1195
+ * await store.waitCondition(condition, { timeoutMillis: 5000, onTimeout: () => { ... } });
1196
+ * ```
1197
+ *
1198
+ * It returns the action which changed the store state into the condition, in case you need it:
1199
+ *
1200
+ * ```ts
1201
+ * let action = await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
1202
+ * ```
1203
+ *
1204
+ * This method is also eventually useful in production code, but note that while it waits,
1205
+ * the condition runs on EVERY state change. A few short-lived waits are fine. But many waits,
1206
+ * or waits that may never complete (especially with no timeout), add a cost to every state
1207
+ * change, for as long as the store lives, since there is no way to cancel a wait. In
1208
+ * production, it's often better to put the logic in an action, or to react to the selected
1209
+ * state in your components.
1210
+ *
1211
+ * Example, in a component:
1212
+ *
1213
+ * ```tsx
1214
+ * function BuyButton() {
1215
+ * const store = useStore();
1216
+ *
1217
+ * async function buy() {
1218
+ * store.dispatch(new BuyStock('IBM'));
1219
+ * await store.waitCondition((state) => state.portfolio.includes('IBM'), { timeoutMillis: 5000 });
1220
+ * showMessage('IBM is now in your portfolio.');
1221
+ * }
1222
+ *
1223
+ * return <button onClick={buy}>Buy IBM</button>;
1224
+ * }
1225
+ * ```
1226
+ *
1227
+ * Note `useStore()` doesn't give you the state. To read the state in a component, use
1228
+ * `useSelect`. In tests, use the store itself (see `Store.waitCondition`).
1229
+ *
1230
+ * See also:
1231
+ * - `waitCondition` - Waits until the state is in a given condition.
1232
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1233
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1234
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1235
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1236
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1237
+ */
1238
+ waitCondition(condition, { timeoutMillis, onTimeout, }) {
1239
+ return this.store.waitCondition(condition, { timeoutMillis, onTimeout });
1240
+ }
1241
+ /**
1242
+ * Returns a Promise that resolves when some actions meet the given `condition`.
1243
+ *
1244
+ * If `completeImmediately` is false (the default), this method will throw an error if the
1245
+ * condition was already true when the method was called. Otherwise, the promise will complete
1246
+ * immediately and throw no error.
1247
+ *
1248
+ * The `condition` is a function that takes the set of actions "in progress", as well as an
1249
+ * action that just entered the set (by being dispatched) or left the set (by finishing
1250
+ * dispatching). The function should return `true` when the condition is met, and `false`
1251
+ * otherwise. For example:
1252
+ *
1253
+ * ```ts
1254
+ * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
1255
+ * ```
1256
+ *
1257
+ * Important: Your condition function should NOT modify the set of actions.
1258
+ *
1259
+ * You get back the set of the actions being dispatched that met the condition, as well as
1260
+ * the action that triggered the condition by being added or removed from the set.
1261
+ *
1262
+ * Note: The condition is only checked when some action is dispatched or finishes dispatching.
1263
+ * It's not checked every time action statuses change.
1264
+ *
1265
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1266
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1267
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1268
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1269
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1270
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1271
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1272
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1273
+ *
1274
+ * Example, in a component:
1275
+ *
1276
+ * ```tsx
1277
+ * function RefreshButton() {
1278
+ * const store = useStore();
1279
+ *
1280
+ * async function refresh() {
1281
+ * store.dispatch(new RefreshPrices());
1282
+ *
1283
+ * // Waits until no RefreshPrices action is in progress.
1284
+ * await store.waitActionCondition(
1285
+ * (actions) => ![...actions].some((action) => action instanceof RefreshPrices),
1286
+ * { timeoutMillis: 5000 });
1287
+ *
1288
+ * showMessage('Prices refreshed.');
1289
+ * }
1290
+ *
1291
+ * return <button onClick={refresh}>Refresh</button>;
1292
+ * }
1293
+ * ```
1294
+ *
1295
+ * See also:
1296
+ * - `waitCondition` - Waits until the state is in a given condition.
1297
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1298
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1299
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1300
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1301
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1302
+ */
1303
+ async waitActionCondition(
1304
+ //
1305
+ /// The condition receives the current actions in progress, and the action that triggered the condition.
1306
+ condition, {
1307
+ // If `completeImmediately` is `false` (the default), this method will throw an error if the
1308
+ // condition is already true when the method is called. Otherwise, the promise will complete
1309
+ // immediately and throw no error.
1310
+ completeImmediately = false,
1311
+ //
1312
+ // The maximum time to wait for the condition to be met. The default is 3 seconds.
1313
+ // To disable the timeout, make it 0 or -1.
1314
+ timeoutMillis = null, onTimeout, } = {}) {
1315
+ return this.store.waitActionCondition(condition, {
1316
+ completeImmediately: completeImmediately,
1317
+ timeoutMillis: timeoutMillis,
1318
+ onTimeout: onTimeout,
1319
+ });
1320
+ }
1321
+ /**
1322
+ * Returns a promise that resolves when ALL given actions finished dispatching.
1323
+ *
1324
+ * If `completeImmediately` is false (the default), this method will throw an error if none
1325
+ * of the given actions are in progress when the method is called. Otherwise, the promise will
1326
+ * complete immediately and throw no error.
1327
+ *
1328
+ * However, if you don't provide any actions (empty list or `null`), the promise will complete
1329
+ * when ALL current actions in progress finish dispatching. In other words, when no actions are
1330
+ * currently in progress. In this case, if [completeImmediately] is `false`, the method will
1331
+ * throw an error if no actions are in progress when the method is called.
1332
+ *
1333
+ * Note: Waiting until no actions are in progress should only be done in test, never in
1334
+ * production, as it's very easy to create a deadlock. However, waiting for specific actions to
1335
+ * finish is safe in production, as long as you're waiting for actions you just dispatched.
1336
+ *
1337
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1338
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1339
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1340
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1341
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1342
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1343
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1344
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1345
+ *
1346
+ * Example, in a component:
1347
+ *
1348
+ * ```tsx
1349
+ * function BuyBothButton() {
1350
+ * const store = useStore();
1351
+ *
1352
+ * async function buyBoth() {
1353
+ * const buyIBM = new BuyStock('IBM');
1354
+ * const buyTSLA = new BuyStock('TSLA');
1355
+ * store.dispatch(buyIBM);
1356
+ * store.dispatch(buyTSLA);
1357
+ * await store.waitAllActions([buyIBM, buyTSLA]);
1358
+ * showMessage('Done.');
1359
+ * }
1360
+ *
1361
+ * return <button onClick={buyBoth}>Buy IBM and TSLA</button>;
1362
+ * }
1363
+ * ```
1364
+ *
1365
+ * See also:
1366
+ * - `waitCondition` - Waits until the state is in a given condition.
1367
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1368
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1369
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1370
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1371
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1372
+ */
1373
+ waitAllActions(actions, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1374
+ return this.store.waitAllActions(actions, {
1375
+ completeImmediately: completeImmediately,
1376
+ timeoutMillis: timeoutMillis,
1377
+ onTimeout: onTimeout,
1378
+ });
1379
+ }
1380
+ /**
1381
+ * Returns a promise that completes when an action of the given type in NOT in progress
1382
+ * (it's not being dispatched):
1383
+ *
1384
+ * - If NO action of the given type is currently in progress when the method is called,
1385
+ * and `completeImmediately` is false (the default), this method will throw an error.
1386
+ *
1387
+ * - If NO action of the given type is currently in progress when the method is called,
1388
+ * and `completeImmediately` is true, the promise completes immediately, returns `null`,
1389
+ * and throws no error.
1390
+ *
1391
+ * - If an action of the given type is in progress, the promise completes when the action
1392
+ * finishes, and returns the action. You can use the returned action to check its `status`:
1393
+ *
1394
+ * ```ts
1395
+ * let action = await store.waitActionType(MyAction);
1396
+ * expect(action?.status.originalError).toBeInstanceOf(UserException);
1397
+ * ```
1398
+ *
1399
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1400
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1401
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1402
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1403
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1404
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1405
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1406
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1407
+ *
1408
+ * You should only use this method in tests. In tests you usually have the store itself,
1409
+ * so see the same method in `Store`, which has more examples.
1410
+ *
1411
+ * See also:
1412
+ * - `waitCondition` - Waits until the state is in a given condition.
1413
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1414
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1415
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1416
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1417
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1418
+ */
1419
+ async waitActionType(actionType, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1420
+ return this.store.waitActionType(actionType, {
1421
+ completeImmediately: completeImmediately,
1422
+ timeoutMillis: timeoutMillis,
1423
+ onTimeout: onTimeout,
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Returns a promise that completes when ALL actions of the given type are NOT in progress
1428
+ * (none of them is being dispatched):
1429
+ *
1430
+ * - If NO action of the given types is currently in progress when the method is called,
1431
+ * and `completeImmediately` is false (the default), this method will throw an error.
1432
+ *
1433
+ * - If NO action of the given type is currently in progress when the method is called,
1434
+ * and `completeImmediately` is true, the promise completes immediately and throws no error.
1435
+ *
1436
+ * - If any action of the given types is in progress, the promise completes only when
1437
+ * no action of the given types is in progress anymore.
1438
+ *
1439
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1440
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1441
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1442
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1443
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1444
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1445
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1446
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1447
+ *
1448
+ * You should only use this method in tests. In tests you usually have the store itself,
1449
+ * so see the same method in `Store`, which has more examples.
1450
+ *
1451
+ * See also:
1452
+ * - `waitCondition` - Waits until the state is in a given condition.
1453
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1454
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1455
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1456
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1457
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1458
+ */
1459
+ async waitAllActionTypes(actionTypes, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1460
+ return this.store.waitAllActionTypes(actionTypes, {
1461
+ completeImmediately: completeImmediately,
1462
+ timeoutMillis: timeoutMillis,
1463
+ onTimeout: onTimeout,
1464
+ });
1465
+ }
1466
+ async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null, onTimeout, } = {}) {
1467
+ return this.store.waitAnyActionTypeFinishes(actionTypes, {
1468
+ timeoutMillis: timeoutMillis,
1469
+ onTimeout: onTimeout,
1470
+ });
1471
+ }
1472
+ }