kiss-for-react 1.1.0 → 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 +54 -30
  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/esm/Store.js DELETED
@@ -1,1606 +0,0 @@
1
- import React, { createContext, useState } from 'react';
2
- import { UserException } from './UserException';
3
- import { ActionStatus } from './KissAction';
4
- import { ProcessPersistence } from './ProcessPersistence';
5
- import { StoreException, TimeoutException } from './StoreException';
6
- import { UnmodifiableSetView } from "./UnmodifiableSetView";
7
- /**
8
- * The store holds the state of the application and allows the state to be updated
9
- * by dispatching actions. The store is also responsible for showing user exceptions
10
- * to the user, persisting the state to the local device disk, processing wait states
11
- * to show spinners while async operations are in progress, and more.
12
- *
13
- * You can create a store with `const store = createStore()` or `const store = new Store()`.
14
- */
15
- export function createStore(params) {
16
- return new Store(params);
17
- }
18
- class RefState {
19
- selectorAndValueAndSetValue;
20
- constructor(selectorAndValueAndSetValue) {
21
- this.selectorAndValueAndSetValue = selectorAndValueAndSetValue;
22
- }
23
- }
24
- class RefStore {
25
- selectorAndValueAndSetValue;
26
- constructor(selectorAndValueAndSetValue) {
27
- this.selectorAndValueAndSetValue = selectorAndValueAndSetValue;
28
- }
29
- }
30
- /**
31
- * The store holds the state of the application and allows the state to be updated
32
- * by dispatching actions. The store is also responsible for showing user exceptions
33
- * to the user, persisting the state to the local device disk, processing wait states
34
- * to show spinners while async operations are in progress, and more.
35
- *
36
- * You can create a store with `const store = createStore()` or `const store = new Store()`.
37
- */
38
- export class Store {
39
- _refStateHooks = new Set();
40
- _refStoreHooks = new Set();
41
- // Rebuilds components because of STATE changes.
42
- //
43
- // We save in the ref:
44
- // - The selector
45
- // - The currently selected value
46
- // - The setValue function
47
- //
48
- // Whenever the state changes, the store will:
49
- // 1. Retrieve all refs
50
- // 2. Apply each selector to the current state to calculate the selected value.
51
- // 3. And compare the selected value with the last selected value.
52
- // 4. If it changed, it calls setValue.
53
- _rebuildFromStateHooks() {
54
- this._refStateHooks.forEach((hookRef) => {
55
- if (hookRef.current) {
56
- const [selector, currentValue, setValue] = hookRef.current.selectorAndValueAndSetValue;
57
- const newSelectedValue = selector(this._state);
58
- if (newSelectedValue !== currentValue) {
59
- setValue(newSelectedValue);
60
- hookRef.current.selectorAndValueAndSetValue[1] = newSelectedValue; // Update the current value in the ref
61
- }
62
- }
63
- });
64
- }
65
- /// Rebuilds components because of `isWaiting`, `isFailed`, `exceptionFor` and `clearExceptionFor`.
66
- //
67
- // We save in the ref:
68
- // - The selector
69
- // - The currently selected value
70
- // - The setValue function
71
- //
72
- // Whenever the store method results changes, the store will:
73
- // 1. Retrieve all refs
74
- // 2. Apply each selector to the current store to calculate the selected value.
75
- // 3. And compare the selected value with the last selected value.
76
- // 4. If it changed, it calls setValue.
77
- _rebuildFromStoreHooks() {
78
- this._refStoreHooks.forEach((hookRef) => {
79
- if (hookRef.current) {
80
- const [selector, currentValue, setValue] = hookRef.current.selectorAndValueAndSetValue;
81
- const newSelectedValue = selector(this);
82
- if (newSelectedValue !== currentValue) {
83
- setValue(newSelectedValue);
84
- hookRef.current.selectorAndValueAndSetValue[1] = newSelectedValue; // Update the current value in the ref
85
- }
86
- }
87
- });
88
- }
89
- /**
90
- * The `Store.log()` is a static function that Kiss uses internally to log information.
91
- * If you want, you can also use it yourself, like this:
92
- *
93
- * ```ts
94
- * Store.log('Some information: ' + someVariable);
95
- * ```
96
- *
97
- * The log function is set during the creation of the store,
98
- * using the `logger` constructor parameter. For example:
99
- *
100
- * ```ts
101
- * const store = new Store<State>({
102
- * initialState: new State(),
103
- * logger: (obj: any) => process.stdout.write(obj + '\n');
104
- * });
105
- * ```
106
- *
107
- * Or using a logger library:
108
- *
109
- * ```ts
110
- * import { Logger } from 'my-logger-library';
111
- *
112
- * const store = new Store<State>({
113
- * initialState: new State(),
114
- * logger: (obj: any) => Logger.log(obj);
115
- * });
116
- * ```
117
- *
118
- * Note, if you don't define a logger yourself, the default is to print
119
- * the log messages to the console with `console.log()`.
120
- *
121
- * This is how you may completely disable the default logger:
122
- *
123
- * ```ts
124
- * const store = new Store<State>({
125
- * initialState: new State(),
126
- * logger: (obj: any) => {};
127
- * });
128
- * ```
129
- */
130
- static log;
131
- _state;
132
- // When true, no actions can be dispatched.
133
- _shutDown = false;
134
- /**
135
- * Set this to `true` when you want to abort any new actions that are dispatched.
136
- * Note this will not stop async actions already running,
137
- * but you can wait for them to finish:
138
- *
139
- * ```ts
140
- * await store.waitAllActions(null, {
141
- * timeoutMillis: 5000,
142
- * completeImmediately: true
143
- * }).catch((error) => { });
144
- * ```
145
- *
146
- * Set this back to `false` to restart the store accepting new action dispatches.
147
- */
148
- setShutDown(shutDown) {
149
- this._shutDown = shutDown;
150
- }
151
- /**
152
- * A queue of errors of type UserException, thrown by actions.
153
- * They are shown to the user using the function `showUserException`.
154
- * This is public if you need it for advanced stuff, but you should probably not touch it.
155
- */
156
- userExceptionsQueue;
157
- /**
158
- * If `true`, will use Store.log() to log all state changes.
159
- * It uses `Store.describeStateChange()` to create the description of those changes.
160
- *
161
- * Note this is true (turned on) by default, as it may be useful for development, testing and
162
- * debugging. Be sure to turn it off in production, as it may slow down your application:
163
- *
164
- * ```ts
165
- * // In production
166
- * const store = new Store<State>({
167
- * initialState: new State(),
168
- * logStateChanges: false,
169
- * });
170
- * ```
171
- */
172
- _logStateChanges;
173
- /**
174
- * The async actions that are currently being processed.
175
- * Use `isWaiting` to know if an action is currently being processed.
176
- */
177
- _actionsInProgress;
178
- /**
179
- * Async actions that we may put into `_asyncActionsInProgress`.
180
- * This helps to know when to rebuild to make `isWaiting` work.
181
- */
182
- _awaitableActions;
183
- /**
184
- * The actions that have failed recently.
185
- * When an action fails by throwing an `UserException`, it's added to this map
186
- * (indexed by its action type), and then removed when it's dispatched.
187
- *
188
- * Use `isFailed`, `exceptionFor` and `clearExceptionFor` to know if you should display
189
- * some error message due to an action failure.
190
- *
191
- * Note: Throwing an `UserException` can show a modal dialog to the user, and also show the error
192
- * as a message in the UI. If you don't want to show the dialog you can use the `noDialog`
193
- * getter in the error message: `throw UserException('Invalid input').noDialog`.
194
- */
195
- _failedActions;
196
- /**
197
- * Async actions that we may put into `_failedActions`.
198
- * This helps to know when to rebuild to make `isWaiting` work.
199
- */
200
- _actionsWeCanCheckFailed;
201
- /**
202
- * Helps implement the waitCondition method.
203
- */
204
- _waitConditions = [];
205
- /**
206
- * Helps implement the `waitActionCondition` method.
207
- */
208
- _waitActionConditions = [];
209
- _processPersistence;
210
- _dispatchCount = 0;
211
- // A function that shows `UserExceptions` to the user, using some UI like a dialog or a toast.
212
- // This function is passed to the constructor. If not passed, the `UserException` is ignored.
213
- _showUserException;
214
- _globalWrapError;
215
- _actionObserver;
216
- _stateObserver;
217
- _errorObserver;
218
- /**
219
- * You can use `store.mocks` to mock actions. You should use this for testing purposes, only.
220
- *
221
- * To mock actions and their reducers, use `store.mocks.add(actionType, mockFunction)`
222
- * multiple times, one for each **action type** you want to mock.
223
- *
224
- * By adding mocks to the store, the `mockFunction` will be called
225
- * to return a mocked action that will be used instead of the original actions, when dispatching.
226
- * You can mock an action to return a specific state, to throw an error,
227
- * or even to abort the action.
228
- *
229
- * Usage:
230
- *
231
- * - `store.mocks.add(actionType, (actionType) => mockAction)`:
232
- * Adds a mock action to the store. Whenever an action of type `actionType` is
233
- * dispatched, `mockAction` will be dispatched instead. If you pass `mockAction` as null,
234
- * actions of type `actionType` will be ignored when dispatched.
235
- *
236
- * - `remove(actionType)`:
237
- * Removes remove a mock action from the store. Note you should pass the
238
- * type of the action that was mocked, and NOT the type of the mock.
239
- *
240
- * - `clear()`:
241
- * Removes all mock actions from the store.
242
- *
243
- * Examples:
244
- *
245
- * ```ts
246
- * // When an IncrementAction is dispatched, AddAction(1) will be dispatched instead.
247
- * store.mocks.add(IncrementAction, (action) => new AddAction(1));
248
- *
249
- * // When an IncrementAction is dispatched, it will be ignored.
250
- * store.mocks.add(IncrementAction, null);
251
- *
252
- * // Removes the mock for Increment.
253
- * store.mocks.remove(Increment);
254
- *
255
- * // Removes all mocks.
256
- * store.mocks.clear();
257
- *
258
- * // When an AddAction is dispatched, the value will be subtracted instead.
259
- * store.mocks.add(AddAction, (action) => new AddAction(-action.value));
260
- * ```ts
261
- */
262
- mocks = new Mocks();
263
- record = {
264
- isRecording: false,
265
- changes: [],
266
- start: () => {
267
- this.record.isRecording = true;
268
- this.record.changes = [];
269
- },
270
- stop: () => {
271
- this.record.isRecording = false;
272
- },
273
- result: () => {
274
- return this.record.changes;
275
- },
276
- toString: () => {
277
- let count = 0;
278
- return '[\n' + this.record.changes.map(change => `${count++}. ` +
279
- `${change.action.constructor.name} ${change.ini ? 'ini(' + change.dispatchCount + ')' : 'end'}: ` +
280
- ((change.ini) ? change.prevState : `${change.prevState} → ${change.newState}`) +
281
- `${change.error ? `, error: ${change.error}` : ''}`).join('\n') + '\n]';
282
- }
283
- };
284
- // The default logger prints messages to the console.
285
- // An alternative is: `const logger = (obj: any) => process.stdout.write(obj + '\n');`
286
- _defaultLogger(obj) {
287
- console.log(obj);
288
- }
289
- ;
290
- // The default Ui just logs all user-exceptions and removes them from the queue.
291
- _defaultShowUserException(exception, _count, next) {
292
- Store.log(`User got an exception: ${exception}`);
293
- next();
294
- }
295
- ;
296
- constructor({ initialState, showUserException, persistor, globalWrapError, actionObserver, stateObserver, errorObserver, logger, logStateChanges, }) {
297
- this._state = initialState;
298
- this._showUserException = showUserException || this._defaultShowUserException;
299
- this._processPersistence = (persistor === undefined) ? null : new ProcessPersistence(persistor, initialState);
300
- this._globalWrapError = globalWrapError;
301
- this._actionObserver = actionObserver;
302
- this._stateObserver = stateObserver;
303
- this._errorObserver = errorObserver;
304
- this.userExceptionsQueue = [];
305
- this._actionsInProgress = new Set();
306
- this._awaitableActions = new Set();
307
- this._failedActions = new Map();
308
- this._actionsWeCanCheckFailed = new Set();
309
- Store.log = logger || this._defaultLogger;
310
- this._logStateChanges = logStateChanges ?? true;
311
- if (this._processPersistence != null) {
312
- this._processPersistence.readInitialState(this, initialState).then();
313
- }
314
- }
315
- get state() {
316
- return this._state;
317
- }
318
- get dispatchCount() {
319
- return this._dispatchCount;
320
- }
321
- /**
322
- * Dispatches the action to the Redux store, to potentially change the state.
323
- *
324
- * See also:
325
- * - `dispatchAll` which dispatches all given actions in parallel.
326
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
327
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
328
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
329
- */
330
- dispatch(action) {
331
- if (this._shutDown) {
332
- Store.log(`Can't dispatch action ${action} because the store is shut down.`);
333
- return;
334
- }
335
- let mockedActionOrAction = this._mockActionOrNot(action);
336
- // 1) If mocked as `null`, the action is ignored.
337
- if (mockedActionOrAction === null)
338
- return; // If mocked as null, the action is ignored.
339
- // 2) If the action wants to abort the dispatch, aborts, swallowing potential errors.
340
- // Note: It's up to the developer to make sure `abortDispatch` doesn't throw any errors.
341
- try {
342
- if (mockedActionOrAction.abortDispatch())
343
- return;
344
- if (mockedActionOrAction.nonReentrant && this.isWaiting(mockedActionOrAction.constructor))
345
- return;
346
- }
347
- catch (error) {
348
- Store.log(`Method '${action}.abortDispatch()' has thrown an error: ${error}.`);
349
- return;
350
- }
351
- // 3) If the action is mocked to return another action, we dispatch the mock.
352
- this._processDispatch(mockedActionOrAction, false);
353
- }
354
- /**
355
- * Dispatches an action and returns a promise that resolves when the action finishes.
356
- * While the state change from the action's reducer will have been applied when the promise
357
- * resolves, other independent processes that the action may have started may still be in
358
- * progress.
359
- *
360
- * Usage: `await store.dispatchAndWait(new MyAction())`.
361
- *
362
- * See also:
363
- * - `dispatch` which dispatches both sync and async actions.
364
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
365
- * - `dispatchAll` which dispatches all given actions in parallel.
366
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
367
- */
368
- dispatchAndWait(action) {
369
- if (this._shutDown) {
370
- Store.log(`Can't dispatch action ${action} because the store is shut down.`);
371
- return Promise.resolve(new ActionStatus());
372
- }
373
- let mockedActionOrAction = this._mockActionOrNot(action);
374
- // 1) If mocked as `null`, the action is ignored.
375
- if (mockedActionOrAction === null)
376
- return Promise.resolve(new ActionStatus());
377
- // 2) If the action wants to abort the dispatch, aborts, swallowing potential errors.
378
- // Note: It's up to the developer to make sure `abortDispatch` doesn't throw any errors.
379
- try {
380
- if (mockedActionOrAction.abortDispatch())
381
- return Promise.resolve(new ActionStatus());
382
- }
383
- catch (error) {
384
- Store.log(`Method '${action}.abortDispatch()' has thrown an error: ${error}.`);
385
- return Promise.resolve(new ActionStatus());
386
- }
387
- // 3) If the action is mocked to return another action, we dispatch the mock.
388
- let promise = mockedActionOrAction._createPromise();
389
- this._processDispatch(mockedActionOrAction, false);
390
- return promise;
391
- }
392
- /**
393
- * Dispatches all given actions in parallel, applying their reducers, and possibly changing
394
- * the store state. The actions may be sync or async. It returns a Promise that resolves when
395
- * ALL actions finish.
396
- *
397
- * ```ts
398
- * let actions = await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
399
- * ```
400
- *
401
- * Note this is exactly the same as doing:
402
- *
403
- * ```ts
404
- * let action1 = new BuyAction('IBM');
405
- * let action2 = new SellAction('TSLA');
406
- * store.dispatch(action1);
407
- * store.dispatch(action2);
408
- * await store.waitAllActions([action1, action2], true);
409
- * let actions = [action1, action2];
410
- * ```
411
- *
412
- * Note: While the state change from the action's reducers will have been applied when the
413
- * Promise resolves, other independent processes that the action may have started may still
414
- * be in progress.
415
- *
416
- * See also:
417
- * - `dispatch` which dispatches both sync and async actions.
418
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
419
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
420
- * - `dispatchAll` which dispatches all given actions in parallel.
421
- */
422
- async dispatchAndWaitAll(actions) {
423
- let promises = [];
424
- for (let action of actions) {
425
- promises.push(this.dispatchAndWait(action));
426
- }
427
- await Promise.all(promises);
428
- return actions;
429
- }
430
- /**
431
- * Dispatches all given actions in parallel, applying their reducer, and possibly changing
432
- * the store state. It returns the same list of actions, so that you can instantiate them
433
- * inline, but still get a list of them.
434
- *
435
- * ```ts
436
- * let actions = store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
437
- * ```
438
- *
439
- * See also:
440
- * - `dispatch` which dispatches both sync and async actions.
441
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
442
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
443
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async. */
444
- dispatchAll(actions) {
445
- for (let action of actions) {
446
- this.dispatch(action);
447
- }
448
- return actions;
449
- }
450
- /**
451
- * Dispatches the given action to the Redux store, to potentially change the state.
452
- *
453
- * This is exactly the same as the regular `dispatch`, except for the fact it
454
- * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
455
- * if any of its `reduce()` or `before()` methods return a Promise.
456
- *
457
- * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
458
- * action is SYNC, which means the state gets changed right after the dispatch call.
459
- *
460
- * See also:
461
- * - `dispatch` which dispatches both sync and async actions.
462
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
463
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
464
- * - `dispatchAll` which dispatches all given actions in parallel.
465
- */
466
- dispatchSync(action) {
467
- if (this._shutDown) {
468
- Store.log(`Can't dispatch action ${action} because the store is shut down.`);
469
- return;
470
- }
471
- let mockedActionOrAction = this._mockActionOrNot(action);
472
- // 1) If mocked as `null`, the action is ignored.
473
- if (mockedActionOrAction === null)
474
- return; // If mocked as null, the action is ignored.
475
- // 2) If the action wants to abort the dispatch, aborts, swallowing potential errors.
476
- // Note: It's up to the developer to make sure `abortDispatch` doesn't throw any errors.
477
- try {
478
- if (mockedActionOrAction.abortDispatch())
479
- return;
480
- }
481
- catch (error) {
482
- Store.log(`Method '${action}.abortDispatch()' has thrown an error: ${error}.`);
483
- return;
484
- }
485
- // 3) If the action is mocked to return another action, we dispatch the mock.
486
- this._processDispatch(mockedActionOrAction, true);
487
- }
488
- // Mocks an action to return another action.
489
- // If it returns null, the action should be ignored by the caller.
490
- // If no mock is defined, the original action is returned unchanged.
491
- _mockActionOrNot(action) {
492
- const mockActionFunction = this.mocks.get(action.constructor);
493
- // If no mock is defined, the original action is returned unchanged.
494
- if (mockActionFunction === undefined) {
495
- return action;
496
- }
497
- // If a mock is defined, we use it.
498
- else {
499
- const mockAction = mockActionFunction(action);
500
- // If the mock returns null, the action is ignored.
501
- if (mockAction === null) {
502
- Store.log(`Dispatch of ${action} aborted by mock.`);
503
- return null;
504
- }
505
- // Otherwise, the mock is used.
506
- else {
507
- Store.log(`Dispatch of ${action} mocked by ${mockAction}.`);
508
- return mockAction;
509
- }
510
- }
511
- }
512
- // Dispatches the action (or the already mocked action).
513
- // If `mustBeSync` is true, will throw a `StoreException` if the action is ASYNC.
514
- _processDispatch(action, mustBeSync) {
515
- if (this._shutDown) {
516
- Store.log(`Can't dispatch action ${action} because the store is shut down.`);
517
- return;
518
- }
519
- this._dispatchCount++;
520
- Store.log(`${this._dispatchCount}) ${action}`);
521
- if (action.status.isDispatched)
522
- throw new StoreException('The action was already dispatched. Please, create a new action each time.');
523
- action._changeStatus({ isDispatched: true });
524
- // We inject the store into the store, so that the action can access it as a property.
525
- action._injectStore(this);
526
- // The action is dispatched twice. This is the 1st: when the action starts (ini true).
527
- this._actionObserver?.(action, this._dispatchCount, true);
528
- // If `record.isRecording`, record the INI state. That's for testing only.
529
- this._record(action, true, this._state, this._state, null);
530
- this._calculateIsWaitingIsFailed(action);
531
- this._wraps(action, () => this._runFromStart(action, mustBeSync));
532
- }
533
- _calculateIsWaitingIsFailed(action) {
534
- // If the action is failable (that is to say, we have once called `isFailed` for this action),
535
- let failable = this._actionsWeCanCheckFailed.has(action.constructor);
536
- let theUIHasAlreadyUpdated = false;
537
- if (failable) {
538
- // Dispatch is starting, so we remove the action from the list of failed actions.
539
- let wasInTheList = this._failedActions.delete(action.constructor);
540
- // Then we notify the UI. Note we don't notify if the action was never checked.
541
- if (wasInTheList) {
542
- theUIHasAlreadyUpdated = true;
543
- this._rebuildFromStoreHooks();
544
- }
545
- }
546
- // Add the action to the list of actions in progress.
547
- this._actionsInProgress.add(action);
548
- // Note: If the UI hasn't updated yet, AND
549
- // the action is awaitable (that is to say, we have already called `isWaiting` for this action),
550
- if (!theUIHasAlreadyUpdated && this._awaitableActions.has(action.constructor)) {
551
- // Then we notify the UI. Note we don't notify if the action was never checked.
552
- this._rebuildFromStoreHooks();
553
- }
554
- }
555
- // Wraps SYNC actions.
556
- // - Runs the before are reduce methods.
557
- // - Runs the state observer.
558
- // - Catches and processes errors.
559
- // - Shows some UI if there are user exceptions.
560
- // - Makes sure the after method runs, always.
561
- // - Removes the wait state for the action in progress, always.
562
- // - Runs the action observer.
563
- _wraps(action, functionToRun) {
564
- let ifWentAsync = false;
565
- try {
566
- ifWentAsync = functionToRun();
567
- }
568
- catch (error) {
569
- this._processWrapsError(error, action);
570
- }
571
- finally {
572
- if (!ifWentAsync) {
573
- this._processWrapsFinally(action);
574
- }
575
- }
576
- }
577
- // Wraps ASYNC actions.
578
- // - Runs the before are reduce methods.
579
- // - Runs the state observer.
580
- // - Catches and processes errors.
581
- // - Shows some UI if there are user exceptions.
582
- // - Makes sure the after method runs, always.
583
- // - Removes the wait state for the action in progress, always.
584
- // - Runs the action observer.
585
- async _wrapsAsync(action, functionToRun) {
586
- try {
587
- await functionToRun();
588
- }
589
- catch (error) {
590
- this._processWrapsError(error, action);
591
- }
592
- finally {
593
- this._processWrapsFinally(action);
594
- }
595
- }
596
- _processWrapsError(error, action) {
597
- //
598
- action._changeStatus({ originalError: error });
599
- // Observe the state with an error here. We use the current state; no new state was applied.
600
- // This is before the action's `after()` and `wrapError()` and `globalWrapError`.
601
- this._stateObserver?.(action, this._state, this._state, error, this._dispatchCount);
602
- this._record(action, false, this._state, this._state, error);
603
- // Any error may optionally be processed by the `wrapError` method of the action.
604
- // Usually this is used to wrap the error inside another that better describes the failed
605
- // action. It's recommended RETURNING the new error, but if `wrapError` throws an error,
606
- // that will be used too.
607
- try {
608
- error = action.wrapError(error);
609
- }
610
- catch (thrownError) {
611
- error = thrownError;
612
- }
613
- if (error !== null) {
614
- // The default wrap error does nothing (returns all errors unaltered).
615
- // Any error may optionally be processed by the `globalWrapError` passed to the Store
616
- // constructor. This is useful to wrap all errors in a common way. It's recommended
617
- // RETURNING the new error, but if `globalWrapError` throws an error, that will be used too.
618
- if (this._globalWrapError != null) {
619
- try {
620
- error = this._globalWrapError(error, action);
621
- }
622
- catch (thrownError) {
623
- error = thrownError;
624
- }
625
- }
626
- // To completely disable the error, `wrapError` or `globalWrapError` may return `null`.
627
- // But if we got an error, we deal with it here.
628
- if (error !== null) {
629
- action._changeStatus({ wrappedError: error });
630
- // Memorizes the action that failed. We'll remove it when it's dispatched again.
631
- this._failedActions.set(action.constructor, action);
632
- // Memorizes errors of type `UserException` (in the error queue).
633
- // These errors are usually shown to the user in a modal dialog, and are not logged.
634
- if (error instanceof UserException) {
635
- if (error.ifOpenDialog) {
636
- this._addUserException(error);
637
- this._openSomeUiToShowUserException();
638
- }
639
- }
640
- // If an error-observer WAS NOT defined in the Store constructor, swallows errors
641
- // of type `UserExceptions` (which were already shown to the user in some UI)
642
- // and rethrows all others. This means the `dispatch()` method will throw this error.
643
- if (!this._errorObserver) {
644
- if (!(error instanceof UserException)) {
645
- throw error;
646
- }
647
- }
648
- // However, if as error-observer WAS defined in the Store constructor,
649
- else {
650
- // We call the error-observer.
651
- // - If it returns `true`, the `dispatch()` method will throw this error.
652
- // - If it returns `false`, the error is swallowed.
653
- // Note: When the error-observer is defined, we don't make a distinction between
654
- // `UserExceptions` and other errors, anymore. We let the error-observer do a
655
- // distinction if it wants by returning true or false depending on the error type.
656
- let shouldThrow = this._errorObserver(error, action, this);
657
- if (shouldThrow)
658
- throw error;
659
- }
660
- }
661
- }
662
- }
663
- _processWrapsFinally(action) {
664
- // We run the `after` method of the action.
665
- try {
666
- action.after();
667
- }
668
- catch (error) {
669
- Store.log(`The after() method of the action ${action} threw an error: ${error}.
670
- This error will be ignored, but you should fix this, as after() methods should not throw errors.`);
671
- }
672
- finally {
673
- action._changeStatus({ hasFinishedMethodAfter: true });
674
- }
675
- // Remove the wait state for the action in progress.
676
- // Note: If the state was applied, this was already removed and the UI updated.
677
- const removed = this._actionsInProgress.delete(action);
678
- if (removed) {
679
- this._rebuildFromStoreHooks();
680
- // Check the wait-conditions after state change. We pass it the trigger-action.
681
- this._checkAllActionConditions(action);
682
- }
683
- // The action is dispatched twice. This is the 2nd: when the action ends (ini false).
684
- this._actionObserver?.(action, this._dispatchCount, false);
685
- // This allows us to `let status = await dispatchAndWait(new MyAction())`.
686
- action._resolvePromise();
687
- }
688
- // This method checks and resolves conditions related to actions in progress.
689
- // It iterates over the `_waitActionConditions` array and checks each condition.
690
- // If a condition is met, it resolves the condition and later removes it.
691
- // The `triggerAction` is the action that was just added or removed in the list
692
- // of `_actionsInProgress` that triggered the check.
693
- _checkAllActionConditions(triggerAction) {
694
- let toRemove = [];
695
- // Iterate over the conditions, resolve the ones that check, and add the ones to be removed to the separate array.
696
- for (let condition of this._waitActionConditions) {
697
- if (condition.check(this.actionsInProgress(), triggerAction)) {
698
- condition.resolve(this.actionsInProgress(), triggerAction);
699
- toRemove.push(condition);
700
- }
701
- }
702
- // Remove the checked conditions from the original array.
703
- if (toRemove.length !== 0)
704
- this._waitActionConditions = this._waitActionConditions.filter(condition => !toRemove.includes(condition));
705
- }
706
- _runFromStart(action, mustBeSync) {
707
- // BEFORE
708
- // 1) Runs the `before` method.
709
- // It may be sync or async, but it doesn't return anything.
710
- let beforeResult = action.before();
711
- // 2) If it's async, wait for the `before` method to finish.
712
- if (beforeResult instanceof Promise) {
713
- if (mustBeSync)
714
- throw new StoreException(`You called dispatchSync(${action.constructor.name}), but the action's 'before' method returned a Promise.`);
715
- this._runAsyncBeforeOnwards(action, beforeResult).then();
716
- return true; // Get out of here. Went ASYNC.
717
- }
718
- action._changeStatus({ hasFinishedMethodBefore: true });
719
- // REDUCE
720
- if (action.ifRetryIsOn)
721
- action.wrapReduce = this._retryWrapReduce(action);
722
- // 3)
723
- // - Runs the SYNC `reduce` method; OR
724
- // - Runs the initial sync part of the ASYNC `reduce` method.
725
- let reduceResult = action.wrapReduce(action.reduce.bind(action))();
726
- // 4) If the reducer returned null, or if it returned the unaltered state, we simply do nothing.
727
- if (reduceResult === null || reduceResult === this.state) {
728
- action._changeStatus({ hasFinishedMethodReduce: true });
729
- this._record(action, false, this.state, this.state, null);
730
- return false; // Kept SYNC.
731
- }
732
- //
733
- // 5) If the reducer is ASYNC, we still process the rest of the reducer to generate the new state.
734
- else if (reduceResult instanceof Promise) {
735
- if (mustBeSync)
736
- throw new StoreException(`You called dispatchSync(${action.constructor.name}), but the action's 'reduce' method returned a Promise.`);
737
- this._runAsyncReduceOnwards(action, reduceResult);
738
- return true; // Get out of here. Went ASYNC.
739
- }
740
- //
741
- // 6) If the reducer is SYNC, we already have the new state, and we simply must apply it.
742
- else {
743
- action._changeStatus({ hasFinishedMethodReduce: true });
744
- if (action.abortReduce(reduceResult)) {
745
- action._changeStatus({ hasFinishedMethodReduce: true });
746
- this._record(action, false, this.state, this.state, null);
747
- return false; // Kept SYNC.
748
- }
749
- this._registerState(action, reduceResult);
750
- return false; // Kept SYNC.
751
- }
752
- }
753
- _retryWrapReduce(action) {
754
- let retry = action.retry;
755
- if (!retry.on) {
756
- function _wrapReduceOff(reduce) {
757
- return reduce;
758
- }
759
- return _wrapReduceOff;
760
- }
761
- //
762
- else {
763
- /// Start with the `initialDelay`, and then increase it by `multiplier` each time this is called.
764
- /// If the delay exceeds `maxDelay`, it will be set to `maxDelay`.
765
- function nextDelay(retry) {
766
- let _multiplier = retry.multiplier;
767
- if (_multiplier <= 1)
768
- _multiplier = 2;
769
- retry.currentDelay = (retry.currentDelay == null) //
770
- ? retry.initialDelay //
771
- : retry.currentDelay * _multiplier;
772
- if (retry.currentDelay > retry.maxDelay)
773
- retry.currentDelay = retry.maxDelay;
774
- return retry.currentDelay;
775
- }
776
- function _wrapReduceRetry(reduce) {
777
- async function _wrapReduceRetryAsync() {
778
- let newState;
779
- try {
780
- newState = reduce();
781
- if (newState instanceof Promise)
782
- newState = await newState;
783
- }
784
- //
785
- catch (error) {
786
- action.retry.attempts++;
787
- let maxRetries = action.retry.maxRetries;
788
- if ((maxRetries >= 0) && (action.attempts > maxRetries))
789
- throw error;
790
- let currentDelay = nextDelay(action.retry);
791
- await new Promise(resolve => setTimeout(resolve, currentDelay));
792
- return action.wrapReduce(reduce)();
793
- }
794
- return newState;
795
- }
796
- return () => _wrapReduceRetryAsync();
797
- }
798
- return _wrapReduceRetry;
799
- }
800
- }
801
- _record(action, ini, prevState, newState, error) {
802
- if (this.record.isRecording) {
803
- this.record.changes.push({
804
- action,
805
- ini,
806
- prevState: prevState,
807
- newState: newState,
808
- error: error,
809
- dispatchCount: this._dispatchCount
810
- });
811
- }
812
- }
813
- async _runAsyncBeforeOnwards(action, beforeResult) {
814
- this._wrapsAsync(action, async () => {
815
- // 2.1) Method `before` is ASYNC, so we wait for it to finish.
816
- await beforeResult;
817
- action._changeStatus({ hasFinishedMethodBefore: true });
818
- // REDUCE
819
- if (action.ifRetryIsOn)
820
- action.wrapReduce = this._retryWrapReduce(action);
821
- // 2.2)
822
- // - Runs the SYNC `reduce` method; OR
823
- // - Runs the initial sync part of the ASYNC `reduce` method.
824
- let reduceResult = action.wrapReduce(action.reduce.bind(action))();
825
- // 2.3) If the reducer returned null, or if it returned the unaltered state, we simply do nothing.
826
- if (reduceResult === null || reduceResult === this.state) {
827
- action._changeStatus({ hasFinishedMethodReduce: true });
828
- this._record(action, false, this.state, this.state, null);
829
- return; // Get out of here.
830
- }
831
- //
832
- // 2.4) If the reducer is ASYNC, we still process the rest of the reducer to generate the new state.
833
- else if (reduceResult instanceof Promise) {
834
- reduceResult = await reduceResult;
835
- action._changeStatus({ hasFinishedMethodReduce: true });
836
- if (reduceResult === null || reduceResult === this.state) {
837
- this._record(action, false, this.state, this.state, null);
838
- }
839
- //
840
- else {
841
- if (action.ifRetryIsOn && !this._isFunction(reduceResult))
842
- throw new StoreException(`Since action '${action}' retries, it should have an ASYNC reducer, that returns a Promise<(St) => St>.`);
843
- let newAsyncState = reduceResult(this.state);
844
- if (newAsyncState != null) {
845
- if (action.abortReduce(newAsyncState)) {
846
- this._record(action, false, this.state, this.state, null);
847
- }
848
- else
849
- this._registerState(action, newAsyncState);
850
- }
851
- }
852
- return; // Get out of here.
853
- }
854
- //
855
- // 2.5) If the reducer is SYNC, we already have the new state, and we simply must apply it.
856
- else {
857
- action._changeStatus({ hasFinishedMethodReduce: true });
858
- if (action.abortReduce(reduceResult)) {
859
- action._changeStatus({ hasFinishedMethodReduce: true });
860
- this._record(action, false, this.state, this.state, null);
861
- }
862
- else
863
- this._registerState(action, reduceResult);
864
- return; // Get out of here.
865
- }
866
- }).then();
867
- }
868
- _runAsyncReduceOnwards(action, reduceResult) {
869
- this._wrapsAsync(action, async () => {
870
- // 5.1) Method `reduce` is ASYNC, so we wait for it to finish.
871
- let functionalReduceResult = await reduceResult;
872
- action._changeStatus({ hasFinishedMethodReduce: true });
873
- // 5.2) If the reducer returned null, we simply do nothing.
874
- if (functionalReduceResult === null) {
875
- this._record(action, false, this.state, this.state, null);
876
- return; // Get out of here.
877
- }
878
- //
879
- // 5.3) If the reducer returned a function `(state: St) => (St | null)`,
880
- // we still need to run this function to generate the new state.
881
- else {
882
- if (action.ifRetryIsOn && !this._isFunction(functionalReduceResult))
883
- throw new StoreException(`Since action '${action}' retries, it should have an ASYNC reducer, that returns a Promise<(St) => St>.`);
884
- let finalReduceState = functionalReduceResult(this.state);
885
- if (finalReduceState != null) {
886
- if (action.abortReduce(finalReduceState)) {
887
- this._record(action, false, this.state, this.state, null);
888
- }
889
- else
890
- this._registerState(action, finalReduceState);
891
- }
892
- return; // Get out of here.
893
- }
894
- }).then();
895
- }
896
- _isFunction(obj) {
897
- return typeof obj === 'function';
898
- }
899
- _registerState(action, newState) {
900
- if (this._logStateChanges) {
901
- try {
902
- let stateChangeDescription = Store.describeStateChange(this.state, newState);
903
- if (stateChangeDescription !== '')
904
- Store.log(stateChangeDescription);
905
- }
906
- catch (error) {
907
- // Swallow error and do nothing, as this is just a debug print.
908
- }
909
- }
910
- const prevState = this._state;
911
- if (newState !== null && newState !== this._state) {
912
- this._state = newState;
913
- this._rebuildFromStateHooks();
914
- // Observe the state with null error, because the reducer completed normally.
915
- this._stateObserver?.(action, prevState, newState, null, this._dispatchCount);
916
- this._record(action, false, prevState, newState, null);
917
- // ---
918
- // Remove the wait state for the action in progress.
919
- // Note: We do this here, before updating the UI.
920
- const removed = this._actionsInProgress.delete(action);
921
- // Check the wait-conditions after state change. We pass it the trigger-action.
922
- if (removed) {
923
- this._rebuildFromStoreHooks();
924
- this._checkAllActionConditions(action);
925
- }
926
- // Check the wait-conditions after state change.
927
- this._waitConditions = this._waitConditions.filter(condition => {
928
- if (condition.check(this.state)) {
929
- // Resolve, returning the action that triggered the condition.
930
- condition.resolve(action);
931
- return false; // remove the condition from the array.
932
- }
933
- return true; // keep the condition in the array.
934
- });
935
- }
936
- if (this._processPersistence != null)
937
- this._processPersistence.process(action, newState);
938
- }
939
- /**
940
- * For this to work, we have to pass a function `showUserException` in the constructor
941
- * of the Store, that will open some UI to show the error to the user.
942
- *
943
- * 1) If the UI is still open, don't do anything.
944
- * 2) If no UI is open, check to see if any errors are in the queue.
945
- * If so, remove the first error from the queue and show it in the UI.
946
- * 3) In this case, we mark the UI as open, and count the number of errors still in the queue.
947
- * 4) When the UI calls `next()`, we mark the UI as closed, and call the method again, to
948
- * process the next error in the queue, if any.
949
- *
950
- * IMPORTANT: Failing to call `next()` will prevent the UI to ever opening again, because
951
- * Kiss will think the previous UI is still open. In contrast, calling `next()` as soon
952
- * as the UI opens may result in opening more than one UI on top pf each other.
953
- * Also, calling `next()` when there are no more errors in the queue will do nothing.
954
- *
955
- * An example using React Native:
956
- *
957
- * ```ts
958
- * const showUserException = (exception: UserException, next: () => void) => {
959
- * Alert.alert(
960
- * exception.title || exception.message,
961
- * exception.title ? exception.message : '',
962
- * [{ text: 'OK', onPress: (_value?: string) => next() }]
963
- * );
964
- * };
965
- * ```
966
- */
967
- _openSomeUiToShowUserException() {
968
- // 1) If the UI is still open, don't do anything.
969
- if (this._isUserExceptionUiOpen)
970
- return;
971
- // 2.1) If no UI is open,
972
- else {
973
- // 2.2) Check to see if any errors are in the queue. If so, remove the first error from the queue.
974
- let currentError = this.userExceptionsQueue.shift();
975
- if (currentError !== undefined) {
976
- // 3.1) In this case, we mark the UI as open,
977
- this._isUserExceptionUiOpen = true;
978
- // 3.2) and count the number of errors still in the queue.
979
- let queued = this.userExceptionsQueue.length;
980
- // 2.3) And show it in the UI.
981
- this._showUserException?.(currentError, queued,
982
- // 4.1) When the UI calls `next()`.
983
- () => {
984
- // 4.2) We mark the UI as closed.
985
- this._isUserExceptionUiOpen = false;
986
- // 4.3) And call the method again, to process the next error in the queue, if any.
987
- this._openSomeUiToShowUserException();
988
- });
989
- }
990
- }
991
- }
992
- ;
993
- _isUserExceptionUiOpen = false;
994
- _addUserException(error) {
995
- this.userExceptionsQueue.push(error);
996
- }
997
- /**
998
- * You can use `isWaiting` and pass it an action `type`:
999
- * - It returns true if an ASYNC action of the specific type is currently being processed.
1000
- * - It returns false if an ASYNC action of the specific type is NOT currently being processed.
1001
- * - This is only useful for ASYNC actions, since it always returns `false` when the action is SYNC.
1002
- *
1003
- * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
1004
- *
1005
- * ```ts
1006
- * dispatch(MyAction());
1007
- * if (store.isWaiting(MyAction)) { // Show a spinner } *
1008
- * ```
1009
- */
1010
- isWaiting(type) {
1011
- this._awaitableActions.add(type);
1012
- for (const action of this._actionsInProgress) {
1013
- if (action instanceof type) {
1014
- return true;
1015
- }
1016
- }
1017
- return false;
1018
- }
1019
- /**
1020
- * Returns true if the given action `type` failed with an `UserException`.
1021
- * Note: This method uses the EXACT action type. Subtypes are not considered.
1022
- */
1023
- isFailed(type) {
1024
- return this.exceptionFor(type) !== null;
1025
- }
1026
- /**
1027
- * Returns the `UserException` of the `type` that failed.
1028
- * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
1029
- */
1030
- exceptionFor(type) {
1031
- this._actionsWeCanCheckFailed.add(type);
1032
- let action = this._failedActions.get(type);
1033
- let error = action?.status.wrappedError;
1034
- return (error instanceof UserException) ? error : null;
1035
- }
1036
- /**
1037
- * Removes the exact given action `type` from the list of action types that failed.
1038
- * Note it clears the EXACT given type. Subtypes are not considered.
1039
- *
1040
- * Even if you never call this method explicitly, just dispatching an action already clears that action type
1041
- * from the list of failing action types. But you can call this method explicitly if you want to clear the
1042
- * action type before it's used again.
1043
- *
1044
- * Usage:
1045
- * ```ts
1046
- * store.clearExceptionFor(MyAction);
1047
- * ```
1048
- */
1049
- clearExceptionFor(type) {
1050
- let result = this._failedActions.delete(type);
1051
- if (result)
1052
- this._rebuildFromStoreHooks();
1053
- }
1054
- /**
1055
- * Function `Store.describeStateChange()` returns a string describing only the differences between
1056
- * two given objects.
1057
- *
1058
- * By default, when `logStateChanges` is set to `true` in the Store constructor, function
1059
- * `describeStateChange` is used together with `Store.log()` to print all state changes to
1060
- * the console. Note you should turn this off in production.
1061
- */
1062
- static describeStateChange(obj1, obj2, path = '') {
1063
- // Ensure both parameters are objects
1064
- if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 == null || obj2 == null) {
1065
- return '';
1066
- // Note: This method should not fail.
1067
- // Throw new StoreException(`Type mismatch or one of the objects is null at path: ${path}`);
1068
- }
1069
- let differences = '';
1070
- // Combine keys from both objects
1071
- const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
1072
- for (const key of allKeys) {
1073
- const val1 = obj1[key];
1074
- const val2 = obj2[key];
1075
- const newPath = path === '' ? key : `${path}.${key}`;
1076
- // If both values are objects, recurse
1077
- if (typeof val1 === 'object' && val1 !== null && typeof val2 === 'object' && val2 !== null) {
1078
- Store.describeStateChange(val1, val2, newPath);
1079
- }
1080
- else {
1081
- // If values are different, log the difference
1082
- if (val1 !== val2) {
1083
- differences += `State ${newPath}: ${val1} → ${val2}; `;
1084
- }
1085
- }
1086
- }
1087
- return differences;
1088
- }
1089
- /**
1090
- * Call `logOut()` when you want to delete the persisted state, and return the store
1091
- * state to the given initial-state. That's usually necessary when the user logs out
1092
- * of your app, or the user deletes its account, so that another user may log in,
1093
- * or start a new sign-up process.
1094
- *
1095
- * Note: If you know about any timers or async processes that you may have started,
1096
- * you should stop/cancel them all before calling this method.
1097
- *
1098
- * You may opt to:
1099
- *
1100
- * - Wait for `throttle` milliseconds to make sure all async processes that the app may
1101
- * have started have time to finish. The default `throttle` is 3000 milliseconds (3 seconds).
1102
- *
1103
- * - Wait for all actions currently running to finish, but wait at most `actionsThrottle`
1104
- * milliseconds. If the actions are not finished by then, the state will be deleted anyway.
1105
- * The default `actionsThrottle` is 6000 milliseconds (6 seconds).
1106
- */
1107
- async logOut({ initialState, throttle = 3000, actionsThrottle = 6000, }) {
1108
- this._processPersistence?.logOut({
1109
- store: this, initialState, throttle, actionsThrottle
1110
- });
1111
- }
1112
- /**
1113
- * Pause the Persistor temporarily.
1114
- *
1115
- * When pausePersistor is called, the Persistor will not start a new persistence process, until method
1116
- * resumePersistor is called. This will not affect the current persistence process, if one is currently
1117
- * running.
1118
- *
1119
- * Note: A persistence process starts when the Persistor.persistDifference method is called,
1120
- * and finishes when the promise returned by that method completes.
1121
- */
1122
- pausePersistor() {
1123
- this._processPersistence?.pause();
1124
- }
1125
- /**
1126
- * Persists the current state (if it's not yet persisted), then pauses the Persistor temporarily.
1127
- *
1128
- * When persistAndPausePersistor is called, this will not affect the current persistence
1129
- * process, if one is currently running. If no persistence process was running, it will
1130
- * immediately start a new persistence process (ignoring Persistor.throttle).
1131
- *
1132
- * Then, the Persistor will not start another persistence process, until method
1133
- * resumePersistor is called.
1134
- *
1135
- * Note: A persistence process starts when the Persistor.persistDifference method is called,
1136
- * and finishes when the promise returned by that method completes.
1137
- */
1138
- persistAndPausePersistor() {
1139
- this._processPersistence?.persistAndPause();
1140
- }
1141
- /**
1142
- * Resumes persistence by the Persistor,
1143
- * after calling pausePersistor or persistAndPausePersistor.
1144
- */
1145
- resumePersistor() {
1146
- this._processPersistence?.resume();
1147
- }
1148
- /**
1149
- * Asks the Persistor to save the initialState in the local persistence.
1150
- */
1151
- async saveInitialStateInPersistence(initialState) {
1152
- return this._processPersistence?.saveInitialState(initialState);
1153
- }
1154
- /**
1155
- * Asks the Persistor to read the state from the local persistence.
1156
- * Important: If you use this, you MUST put this state into the store.
1157
- * Kiss will assume that's the case, and will not work properly otherwise.
1158
- */
1159
- async readStateFromPersistence() {
1160
- return this._processPersistence?.readState() || null;
1161
- }
1162
- /**
1163
- * Asks the Persistor to delete the saved state from the local persistence.
1164
- */
1165
- async deleteStateFromPersistence() {
1166
- return this._processPersistence?.deleteState();
1167
- }
1168
- /**
1169
- * Gets, from the Persistor, the last state that was saved to the local persistence.
1170
- */
1171
- getLastPersistedStateFromPersistor() {
1172
- return this._processPersistence?.lastPersistedState || null;
1173
- }
1174
- /**
1175
- * Returns a promise which will resolve when the given state `condition` is true.
1176
- * If the condition is already true when the method is called, the promise resolves immediately.
1177
- *
1178
- * You may also provide a `timeoutMillis`, which by default is 10 minutes. If you want, you
1179
- * can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1180
- * To disable the timeout, make it 0 or -1.
1181
- *
1182
- * This method is useful in tests, and it returns the action which changed
1183
- * the store state into the condition, in case you need it:
1184
- *
1185
- * ```typescript
1186
- * let action = await store.waitCondition((state) => state.name == "Bill");
1187
- * expect(action instanceof ChangeNameAction).toBe(true);
1188
- * ```
1189
- *
1190
- * This method is also eventually useful in production code, in which case you
1191
- * should avoid waiting for conditions that may take a very long time to complete,
1192
- * as checking the condition is an overhead to every state change.
1193
- *
1194
- * Examples:
1195
- *
1196
- * // Dispatch actions and wait for the state change:
1197
- * expect(store.state.user.isLoggedIn).toBe(false);
1198
- * dispatch(new LogInUser("Mary"));
1199
- * await store.waitCondition((state) => state.user.isLoggedIn);
1200
- * expect(store.state.user.name, "Mary");
1201
- *
1202
- * See also:
1203
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1204
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1205
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1206
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1207
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1208
- */
1209
- async waitCondition(condition, timeoutMillis = null) {
1210
- // If the condition is already met, return immediately.
1211
- // Return `null` because there was no trigger action that changed the state into the condition.
1212
- if (condition(this._state))
1213
- return null;
1214
- // Otherwise, create a Promise that resolves when the condition is met.
1215
- else {
1216
- return new Promise((resolve, reject) => {
1217
- this._waitConditions.push({ check: condition, resolve });
1218
- timeoutMillis ??= TimeoutException.defaultTimeoutMillis;
1219
- if (timeoutMillis > 0) {
1220
- setTimeout(() => {
1221
- reject(new TimeoutException(`Timeout exceeded: ${timeoutMillis} milliseconds.`));
1222
- }, timeoutMillis);
1223
- }
1224
- });
1225
- }
1226
- }
1227
- /**
1228
- * Returns a Promise that resolves when some actions meet the given `condition`.
1229
- *
1230
- * If `completeImmediately` is false (the default), this method will throw an error if the
1231
- * condition was already true when the method was called. Otherwise, the promise will complete
1232
- * immediately and throw no error.
1233
- *
1234
- * The `condition` is a function that takes the set of actions "in progress", as well as an
1235
- * action that just entered the set (by being dispatched) or left the set (by finishing
1236
- * dispatching). The function should return `true` when the condition is met, and `false`
1237
- * otherwise. For example:
1238
- *
1239
- * ```ts
1240
- * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
1241
- * ```
1242
- *
1243
- * Note: Your condition function should NOT try and modify the set of actions it got in
1244
- * the `actionsInProgress` parameter. If you do, Kiss will throw an error.
1245
- *
1246
- * You get back the set of the actions being dispatched that met the condition, as well as
1247
- * the action that triggered the condition by being added or removed from the set.
1248
- *
1249
- * Note: The condition is only checked when some action is dispatched or finishes dispatching.
1250
- * It's not checked every time action statuses change.
1251
- *
1252
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
1253
- * To disable the timeout, make it 0 or -1.
1254
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1255
- *
1256
- * See also:
1257
- * `waitCondition` - Waits until the state is in a given condition.
1258
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1259
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1260
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1261
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1262
- *
1263
- * You should only use this method in tests.
1264
- */
1265
- async waitActionCondition(
1266
- //
1267
- /// The condition receives the current actions in progress, and the action that triggered the condition.
1268
- condition, {
1269
- // If `completeImmediately` is `false` (the default), this method will throw an error if the
1270
- // condition is already true when the method is called. Otherwise, the promise will complete
1271
- // immediately and throw no error.
1272
- completeImmediately = false,
1273
- //
1274
- // Error message in case the condition was already true when the method was called,
1275
- // and `completeImmediately` is false.
1276
- completedErrorMessage = "Awaited action condition was already true",
1277
- //
1278
- // The maximum time to wait for the condition to be met. The default is 10 minutes.
1279
- // To disable the timeout, make it 0 or -1.
1280
- timeoutMillis = null, } = {}) {
1281
- // If the condition is already true when `waitActionCondition` is called,
1282
- if (condition(this.actionsInProgress(), null)) {
1283
- // Complete and return the actions in progress and the trigger action.
1284
- if (completeImmediately)
1285
- return Promise.resolve({ actions: this.actionsInProgress(), triggerAction: null });
1286
- // else throw an error.
1287
- else
1288
- throw new StoreException(completedErrorMessage + ", and the promise completed immediately.");
1289
- }
1290
- //
1291
- else {
1292
- return new Promise((resolve, reject) => {
1293
- this._waitActionConditions.push({
1294
- check: (actions, triggerAction) => condition(actions, triggerAction),
1295
- resolve: (actions, triggerAction) => resolve({ actions, triggerAction: triggerAction })
1296
- });
1297
- timeoutMillis ??= TimeoutException.defaultTimeoutMillis;
1298
- if (timeoutMillis > 0) {
1299
- setTimeout(() => {
1300
- reject(new TimeoutException(`Timeout exceeded: ${timeoutMillis} milliseconds.`));
1301
- }, timeoutMillis);
1302
- }
1303
- });
1304
- }
1305
- }
1306
- /**
1307
- * Returns a promise that resolves when ALL given actions finished dispatching.
1308
- *
1309
- * If `completeImmediately` is false (the default), this method will throw an error if none
1310
- * of the given actions are in progress when the method is called. Otherwise, the promise will
1311
- * complete immediately and throw no error.
1312
- *
1313
- * However, if you don't provide any actions (empty list or `null`), the promise will complete
1314
- * when ALL current actions in progress finish dispatching. In other words, when no actions are
1315
- * currently in progress. In this case, if [completeImmediately] is `false`, the method will
1316
- * throw an error if no actions are in progress when the method is called.
1317
- *
1318
- * Note: Waiting until no actions are in progress should only be done in test, never in
1319
- * production, as it's very easy to create a deadlock. However, waiting for specific actions to
1320
- * finish is safe in production, as long as you're waiting for actions you just dispatched.
1321
- *
1322
- * You may also provide a [timeoutMillis], which by default is 10 minutes.
1323
- * To disable the timeout, make it 0 or -1.
1324
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1325
- *
1326
- * Examples:
1327
- *
1328
- * ```ts
1329
- * // Dispatch actions in PARALLEL and wait until no actions are in progress.
1330
- * expect(state.stocks).toEqual(['TSLA']);
1331
- * dispatch(new BuyAction('IBM'));
1332
- * dispatch(new SellAction('TSLA'));
1333
- * await waitAllActions([]);
1334
- * expect(state.stocks).toEqual(['IBM']);
1335
- *
1336
- * // Dispatch two actions in PARALLEL and wait for them to finish:
1337
- * expect(state.stocks).toEqual(['TSLA']);
1338
- * let action1 = new BuyAction('IBM');
1339
- * let action2 = new SellAction('TSLA');
1340
- * dispatch(action1);
1341
- * dispatch(action2);
1342
- * await store.waitAllActions([action1, action2]);
1343
- * expect(state.stocks).toEqual(['IBM']);
1344
- *
1345
- * // This could also have been achieved by dispatching two actions in PARALLEL
1346
- * // by using with `dispatchAndWaitAll` to wait for them:
1347
- * expect(state.stocks).toEqual(['TSLA']);
1348
- * await dispatchAndWaitAll([
1349
- * new SellAction('IBM'),
1350
- * new BuyAction('TSLA')
1351
- * ]);
1352
- * expect(state.stocks).toEqual(['IBM']);
1353
- *
1354
- * // This could also have been achieved by dispatching two actions in SERIES
1355
- * // by using `dispatchAndWait` to wait for them:
1356
- * expect(state.stocks).toEqual(['TSLA']);
1357
- * await dispatchAndWait(new BuyAction('IBM'));
1358
- * await dispatchAndWait(new SellAction('TSLA'));
1359
- * expect(state.stocks).toEqual(['IBM']);
1360
- * ```
1361
- *
1362
- * See also:
1363
- * `waitCondition` - Waits until the state is in a given condition.
1364
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1365
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1366
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1367
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1368
- *
1369
- * You should only use this method in tests.
1370
- */
1371
- async waitAllActions(actions, { completeImmediately = false, timeoutMillis = null } = {}) {
1372
- if (!actions || (actions.length === 0)) {
1373
- return this.waitActionCondition((actions) => actions.size === 0, {
1374
- completeImmediately: completeImmediately,
1375
- completedErrorMessage: "No actions were in progress",
1376
- timeoutMillis: timeoutMillis,
1377
- });
1378
- }
1379
- else {
1380
- return this.waitActionCondition((actionsInProgress) => {
1381
- for (const action of actions) {
1382
- if (actionsInProgress.has(action)) {
1383
- return false;
1384
- }
1385
- }
1386
- return true;
1387
- }, {
1388
- completeImmediately: completeImmediately,
1389
- completedErrorMessage: "None of the given actions were in progress",
1390
- timeoutMillis: timeoutMillis,
1391
- });
1392
- }
1393
- }
1394
- /**
1395
- * Returns a promise that completes when an action of the given type in NOT in progress
1396
- * (it's not being dispatched):
1397
- *
1398
- * - If NO action of the given type is currently in progress when the method is called,
1399
- * and `completeImmediately` is false (the default), this method will throw an error.
1400
- *
1401
- * - If NO action of the given type is currently in progress when the method is called,
1402
- * and `completeImmediately` is true, the promise completes immediately, returns `null`,
1403
- * and throws no error.
1404
- *
1405
- * - If an action of the given type is in progress, the promise completes when the action
1406
- * finishes, and returns the action. You can use the returned action to check its `status`:
1407
- *
1408
- * ```dart
1409
- * var action = await store.waitActionType(MyAction);
1410
- * expect(action.status.originalError, isA<UserException>());
1411
- * ```
1412
- *
1413
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
1414
- * To disable the timeout, make it 0 or -1.
1415
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1416
- *
1417
- * Examples:
1418
- *
1419
- * ```ts
1420
- * // Wait until some action of a given type is dispatched.
1421
- * dispatch(new DoALotOfStuffAction());
1422
- * let action = await store.waitActionType(ChangeNameAction);
1423
- * expect(action instanceof ChangeNameAction).toBe(true);
1424
- * expect(action.status.isCompletedOk).toBe(true);
1425
- * expect(store.state.name).toBe('Bill');
1426
- * ```
1427
- *
1428
- * See also:
1429
- * `waitCondition` - Waits until the state is in a given condition.
1430
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1431
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1432
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1433
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1434
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1435
- *
1436
- * You should only use this method in tests.
1437
- */
1438
- async waitActionType(actionType, { completeImmediately = false, timeoutMillis = null } = {}) {
1439
- let { actions, triggerAction } = await this.waitActionCondition((actionsInProgress, triggerAction) => {
1440
- return !(Array.from(actionsInProgress).some((action) => action.constructor === actionType));
1441
- }, {
1442
- completeImmediately: completeImmediately,
1443
- completedErrorMessage: "No action of the given type was in progress",
1444
- timeoutMillis: timeoutMillis,
1445
- });
1446
- return triggerAction;
1447
- }
1448
- /**
1449
- * Returns a promise that completes when ALL actions of the given type are NOT in progress
1450
- * (none of them is being dispatched):
1451
- *
1452
- * - If NO action of the given types is currently in progress when the method is called,
1453
- * and `completeImmediately` is false (the default), this method will throw an error.
1454
- *
1455
- * - If NO action of the given type is currently in progress when the method is called,
1456
- * and `completeImmediately` is true, the promise completes immediately and throws no error.
1457
- *
1458
- * - If any action of the given types is in progress, the promise completes only when
1459
- * no action of the given types is in progress anymore.
1460
- *
1461
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
1462
- * To disable the timeout, make it 0 or -1.
1463
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1464
- *
1465
- * Examples:
1466
- *
1467
- * ```ts
1468
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
1469
- * expect(store.state.portfolio).toEqual(['TSLA']);
1470
- * dispatch(new BuyAction('IBM'));
1471
- * dispatch(new SellAction('TSLA'));
1472
- * await store.waitAllActionTypes([BuyAction, SellAction]);
1473
- * expect(store.state.portfolio).toEqual(['IBM']);
1474
- * ```
1475
- *
1476
- * See also:
1477
- * `waitCondition` - Waits until the state is in a given condition.
1478
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1479
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1480
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1481
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1482
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1483
- *
1484
- * You should only use this method in tests.
1485
- */
1486
- async waitAllActionTypes(actionTypes, { completeImmediately = false, timeoutMillis = null } = {}) {
1487
- if (actionTypes.length === 0) {
1488
- await this.waitActionCondition((actions, triggerAction) => actions.size === 0, {
1489
- completeImmediately: completeImmediately,
1490
- completedErrorMessage: "No actions are in progress",
1491
- timeoutMillis: timeoutMillis,
1492
- });
1493
- }
1494
- else {
1495
- await this.waitActionCondition((actionsInProgress, triggerAction) => {
1496
- for (const actionType of actionTypes) {
1497
- if (Array.from(actionsInProgress).some(action => action.constructor === actionType))
1498
- return false;
1499
- }
1500
- return true;
1501
- }, {
1502
- completeImmediately: completeImmediately,
1503
- completedErrorMessage: "No action of the given types was in progress",
1504
- timeoutMillis: timeoutMillis,
1505
- });
1506
- }
1507
- }
1508
- /**
1509
- * Returns a promise which will complete when ANY action of the given types FINISHES
1510
- * dispatching. IMPORTANT: This method is different from the other similar methods, because
1511
- * it does NOT complete immediately if no action of the given types is in progress. Instead,
1512
- * it waits until an action of the given types finishes dispatching, even if they
1513
- * were not yet in progress when the method was called.
1514
- *
1515
- * This method returns the action that completed the promise, which you can use to check
1516
- * its `status`.
1517
- *
1518
- * It's useful when the actions you are waiting for are not yet dispatched when you call this
1519
- * method. For example, suppose action `StartAction` starts a process that takes some time
1520
- * to run and then dispatches an action called `MyFinalAction`. You can then write:
1521
- *
1522
- * ```dart
1523
- * dispatch(StartAction());
1524
- * let action = await store.waitAnyActionTypeFinishes([MyFinalAction]);
1525
- * expect(action.status.originalError).toBeInstanceOf(UserException>);
1526
- * ```
1527
- *
1528
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
1529
- * To disable the timeout, make it 0 or -1.
1530
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
1531
- *
1532
- * Examples:
1533
- *
1534
- * ```ts
1535
- * // Wait until some action of the given types is dispatched.
1536
- * dispatch(new ProcessStocksAction());
1537
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
1538
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
1539
- * ```
1540
- *
1541
- * See also:
1542
- * `waitCondition` - Waits until the state is in a given condition.
1543
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1544
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1545
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
1546
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1547
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1548
- *
1549
- * You should only use this method in tests.
1550
- */
1551
- async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null }) {
1552
- const { triggerAction } = await this.waitActionCondition(
1553
- //
1554
- (actionsInProgress, triggerAction) => {
1555
- // If the triggerAction is one of the actionTypes,
1556
- if ((triggerAction !== null) && actionTypes.includes(triggerAction.constructor)) {
1557
- // If the actions in progress do not contain the triggerAction, then the triggerAction has finished.
1558
- // Otherwise, the triggerAction has just been dispatched, which is not what we want.
1559
- const isFinished = !Array.from(actionsInProgress).includes(triggerAction);
1560
- return isFinished;
1561
- }
1562
- return false;
1563
- }, {
1564
- completedErrorMessage: "Assertion error",
1565
- timeoutMillis: timeoutMillis,
1566
- });
1567
- // Always non-null, because the condition is only met when an action finishes.
1568
- return triggerAction;
1569
- }
1570
- /**
1571
- * Returns an unmodifiable set of the actions on progress.
1572
- * For debug purposes, the `toString` method of the returned set will
1573
- * call `KissAction.toString()` for all actions.
1574
- */
1575
- actionsInProgress() {
1576
- return new UnmodifiableSetView(this._actionsInProgress);
1577
- }
1578
- /**
1579
- * Waits until the store state meets a certain condition, and then dispatches an action.
1580
- */
1581
- dispatchWhen(action, condition) {
1582
- this.waitCondition(condition).then(() => this.dispatch(action));
1583
- }
1584
- }
1585
- export const StoreContext = createContext({
1586
- store: null
1587
- });
1588
- export function StoreProvider({ store, children }) {
1589
- const [_store] = useState(store);
1590
- return (React.createElement(StoreContext.Provider, { value: { store: _store } }, children));
1591
- }
1592
- class Mocks {
1593
- mocks = new Map();
1594
- add(actionType, mockFunction) {
1595
- this.mocks.set(actionType, mockFunction);
1596
- }
1597
- remove(actionType) {
1598
- this.mocks.delete(actionType);
1599
- }
1600
- clear() {
1601
- this.mocks.clear();
1602
- }
1603
- get(actionType) {
1604
- return this.mocks.get(actionType);
1605
- }
1606
- }