kiss-for-react 1.1.0 → 2.0.1

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 +293 -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 +1474 -969
  13. package/lib/cjs/KissAction.js +4762 -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 +4342 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +166 -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 +5257 -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 +2266 -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 +95 -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 +288 -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 +1448 -0
  80. package/lib/esm/KissAction.mjs +4816 -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 +4464 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +162 -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 +5257 -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 +2266 -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 +95 -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
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoadPages = exports.Pages = void 0;
4
+ const KissAction_1 = require("./KissAction");
5
+ const StoreException_1 = require("./StoreException");
6
+ /**
7
+ * The pages of a list loaded page by page, to keep in the state. It's created and changed by a
8
+ * `LoadPages` action, and it's immutable: each load puts a new `Pages` in the state.
9
+ *
10
+ * - `pages` are the pages loaded so far, in order. Each page is whatever `loadPage` returned
11
+ * (an array of items, or an object with the items and some information from the server).
12
+ * - `pageParams` are the page params (cursors, page numbers, etc.) used to load each page.
13
+ * `pageParams[i]` loaded `pages[i]`.
14
+ * - `hasNextPage` is `true` if there is a page after the last one, as told by `nextPageParam`.
15
+ * - `hasPreviousPage` is `true` if there is a page before the first one, as told by
16
+ * `previousPageParam`. It's always `false` if the action doesn't implement it.
17
+ *
18
+ * Start with `Pages.empty()` in the initial state (or with `null`, since `getPagesFromState`
19
+ * may return `null` when nothing was loaded yet). To show the items, flatten the pages in the
20
+ * component: `pages.pages.flat()`, or `pages.pages.flatMap(page => page.items)`.
21
+ *
22
+ * To change the pages yourself (for example, to remove an item that was deleted), use `copy`
23
+ * with the new `pages` array. Keep `pageParams` with one param per page, since a `refresh`
24
+ * reloads the pages with them.
25
+ *
26
+ * If you persist the state with a `ClassPersistor`, add `Pages` to its classes.
27
+ */
28
+ class Pages {
29
+ constructor(pages = [], pageParams = [], hasNextPage = false, hasPreviousPage = false) {
30
+ this.pages = pages;
31
+ this.pageParams = pageParams;
32
+ this.hasNextPage = hasNextPage;
33
+ this.hasPreviousPage = hasPreviousPage;
34
+ }
35
+ /** No pages loaded yet. Dispatching `next`, `previous` or `refresh` then loads the first page. */
36
+ static empty() {
37
+ return new Pages();
38
+ }
39
+ /** True if no page was loaded. */
40
+ get isEmpty() {
41
+ return this.pages.length === 0;
42
+ }
43
+ /** Returns a copy with the given changes. */
44
+ copy(changes) {
45
+ return new Pages(changes.pages ?? this.pages, changes.pageParams ?? this.pageParams, changes.hasNextPage ?? this.hasNextPage, changes.hasPreviousPage ?? this.hasPreviousPage);
46
+ }
47
+ toString() {
48
+ return `Pages(${this.pages.length} pages, hasNextPage: ${this.hasNextPage}, hasPreviousPage: ${this.hasPreviousPage})`;
49
+ }
50
+ }
51
+ exports.Pages = Pages;
52
+ /**
53
+ * Base class for actions that load a list page by page: a "load more" button, or an infinite
54
+ * scroll. It keeps the loaded pages in the state, in a `Pages` value, and knows how to load the
55
+ * next page, the previous page, the first page again, or all the loaded pages again.
56
+ *
57
+ * Your action says where the pages are in the state, what the first page param is, how to
58
+ * load a page, and how to get the param of the next page from the last page loaded:
59
+ *
60
+ * ```ts
61
+ * class LoadTodos extends LoadPages<State, Todo[], string | null> {
62
+ * getPagesFromState(state: State) { return state.todos; } // Pages<Todo[], string | null>
63
+ * applyPagesToState(state: State, todos: Pages<Todo[], string | null>) { return state.copy({ todos }); }
64
+ * initialPageParam() { return null; } // The first page has no cursor.
65
+ * loadPage(cursor: string | null) { return api.todosAfter(cursor, 20); } // 20 items with id > cursor.
66
+ * nextPageParam(lastPage: Todo[]) { return lastPage.length < 20 ? null : lastPage.at(-1)!.id; } // null = no more.
67
+ * }
68
+ * ```
69
+ *
70
+ * The page param can be anything: the id of the last item (as above), a page number, or an
71
+ * opaque cursor from the server. If the server returns the cursor of the next page with each
72
+ * page, make the page an object with it, like `{ items: Todo[], nextCursor: string | null }`,
73
+ * and return `lastPage.nextCursor` from `nextPageParam`.
74
+ *
75
+ * Dispatch it with the pages to load (see `PagesToLoad`):
76
+ *
77
+ * ```ts
78
+ * dispatch(new LoadTodos()); // Same as 'refresh'. When mounting the screen.
79
+ * dispatch(new LoadTodos('next')); // The "load more" button, or the end of the scroll.
80
+ * dispatch(new LoadTodos('first')); // Start over: a pull-to-refresh, or when a filter changes.
81
+ * dispatch(new LoadTodos('previous')); // Only if `previousPageParam` is implemented.
82
+ * ```
83
+ *
84
+ * - `'refresh'` loads again the pages that are in the state, one after the other from the
85
+ * first, using the param of the first page and then the params `nextPageParam` gives for
86
+ * each new page (so the pages stay consistent if items were added or removed). The state
87
+ * only changes at the end, with all the pages. It stops early if `nextPageParam` says there
88
+ * are no more pages. If no page was loaded yet, it loads the first page. So, it's safe to
89
+ * dispatch it whenever the screen is shown, or the app comes back to the foreground,
90
+ * together with `fresh`, to skip it when the data is recent.
91
+ *
92
+ * - `'next'` loads the page after the last one and adds it to the end. If there is no next
93
+ * page (`pages.hasNextPage` is `false`), nothing is loaded (the dispatch is aborted). If no
94
+ * page was loaded yet, it loads the first page.
95
+ *
96
+ * - `'previous'` is the same, for the page before the first one, and adds it to the start.
97
+ * Implement `previousPageParam` to use it. For example, a chat that starts at the newest
98
+ * messages and loads the older ones upward.
99
+ *
100
+ * - `'first'` loads the first page, with `initialPageParam()`, and throws away the other
101
+ * pages.
102
+ *
103
+ * ## In the component
104
+ *
105
+ * ```tsx
106
+ * const todos = useSelect((state: State) => state.todos); // A `Pages<Todo[], string | null>`.
107
+ * const isLoading = useIsWaiting(LoadTodos);
108
+ * const items = todos.pages.flat();
109
+ * ...
110
+ * <button disabled={!todos.hasNextPage || isLoading} onClick={() => dispatch(new LoadTodos('next'))}>
111
+ * {isLoading ? 'Loading...' : 'Load more'}
112
+ * </button>
113
+ * ```
114
+ *
115
+ * ## Only one load per list at a time
116
+ *
117
+ * While a `LoadTodos` is running, a `'next'` or `'previous'` dispatched for the same list is
118
+ * aborted, as if it was not dispatched: two quick taps on "load more" load one page, and a
119
+ * scroll handler can dispatch `'next'` freely. A `'first'` or `'refresh'` instead aborts the
120
+ * loads of the same list that are running, and runs: the newest request wins. The aborted
121
+ * action's `abortSignal` is aborted, so pass it to `fetch` in `loadPage` to cancel its request.
122
+ *
123
+ * ## Several lists with the same action
124
+ *
125
+ * If the same action class loads different lists (one per user, per tab, etc.), override
126
+ * `pagesKeyParams()` to tell them apart. Loads of different keys don't affect each other, and
127
+ * the key is also the `statusKey` of the action, so `useIsWaiting(LoadTodos, { statusKey })`
128
+ * tells if that list is loading:
129
+ *
130
+ * ```ts
131
+ * class LoadComments extends LoadPages<State, Comment[], number> {
132
+ * constructor(readonly postId: string, which: PagesToLoad = 'refresh') { super(which); }
133
+ * pagesKeyParams() { return this.postId; }
134
+ * getPagesFromState(state: State) { return state.commentsOf(this.postId); }
135
+ * ...
136
+ * }
137
+ * ```
138
+ *
139
+ * ## Limiting the pages in memory
140
+ *
141
+ * Set `maxPages` to keep at most that many pages. When a `'next'` page is added past the
142
+ * limit, the first page is dropped (and when a `'previous'` page is added, the last one). A
143
+ * `'refresh'` then only reloads the pages kept. Implement `previousPageParam` too, so that the
144
+ * user can load the dropped pages again by scrolling back.
145
+ *
146
+ * ## With the other features
147
+ *
148
+ * - `fresh` and `throttle` only apply to `'first'` and `'refresh'`: a `'next'` or `'previous'`
149
+ * always runs, since loading more is never "the same data again" (it also starts a new fresh
150
+ * period). If you override `ignoreFresh` or `ignoreThrottle`, keep that: for example,
151
+ * `get ignoreFresh() { return this.force || super.ignoreFresh; }`.
152
+ * - `retry`, `checkInternet` and `debounce` work as usual. With `retry`, the whole load is
153
+ * retried (all the pages of a `'refresh'`).
154
+ * - It should not be combined with `nonReentrant` or `ignoreOld`, since it already decides
155
+ * which loads run. Dispatching it with those throws a `StoreException`.
156
+ * - To poll a list, override `createPollingAction()` to return a `'refresh'`.
157
+ * - Do not override `reduce`, `abortDispatch` or `statusKey`.
158
+ */
159
+ class LoadPages extends KissAction_1.KissAction {
160
+ constructor(which = 'refresh') {
161
+ super();
162
+ this.which = which;
163
+ }
164
+ /**
165
+ * By default, all the actions of the class load the same list. Override `pagesKeyParams()`
166
+ * to return a field (or an array of fields) when the same class loads different lists, so
167
+ * that their loads don't affect each other:
168
+ *
169
+ * ```ts
170
+ * pagesKeyParams() { return this.postId; }
171
+ * ```
172
+ *
173
+ * The result is also the `statusKey` of the action, so that
174
+ * `useIsWaiting(LoadComments, { statusKey: postId })` tells if the list of that post is
175
+ * loading.
176
+ *
177
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
178
+ * by their contents.
179
+ */
180
+ pagesKeyParams() {
181
+ return null;
182
+ }
183
+ /** The `statusKey` is `pagesKeyParams()`. Do NOT override this; override `pagesKeyParams()`. */
184
+ get statusKey() {
185
+ return this.pagesKeyParams();
186
+ }
187
+ /** A `'next'` or `'previous'` always runs, even if the list is fresh. See `LoadPages`. */
188
+ get ignoreFresh() {
189
+ return this._loadsMore;
190
+ }
191
+ /** A `'next'` or `'previous'` always runs, even if the list is throttled. See `LoadPages`. */
192
+ get ignoreThrottle() {
193
+ return this._loadsMore;
194
+ }
195
+ /** True if `which` is `'next'` or `'previous'`. */
196
+ get _loadsMore() {
197
+ return this.which === 'next' || this.which === 'previous';
198
+ }
199
+ /**
200
+ * Do NOT override this method. A `'next'` or `'previous'` is aborted if another load of the
201
+ * same list is running, or if there is no page to load in that direction.
202
+ */
203
+ abortDispatch() {
204
+ if (!this._loadsMore)
205
+ return false;
206
+ // Another load of the same list is running. Note this action is not in progress yet.
207
+ if (this.store.isWaiting(this._type, { statusKey: this.statusKey }))
208
+ return true;
209
+ // There is no page to load in that direction. But when no page was loaded yet, the first
210
+ // page is loaded.
211
+ const pages = this.getPagesFromState(this.state);
212
+ if (pages == null || pages.isEmpty)
213
+ return false;
214
+ return !(this.which === 'previous' ? pages.hasPreviousPage : pages.hasNextPage);
215
+ }
216
+ /**
217
+ * Do NOT override this method. Implement `getPagesFromState`, `applyPagesToState`,
218
+ * `initialPageParam`, `loadPage` and `nextPageParam` instead.
219
+ */
220
+ async reduce() {
221
+ // A `'first'` or `'refresh'` aborts the other loads of the same list, so that the newest
222
+ // request wins. The results of the aborted ones are ignored.
223
+ if (!this._loadsMore)
224
+ this._abortOtherLoads();
225
+ const old = this.getPagesFromState(this.state) ?? Pages.empty();
226
+ if (this._loadsMore && !old.isEmpty)
227
+ return this._loadOneMore(old);
228
+ const loaded = await this._loadFromStart(old);
229
+ return (state) => this.applyPagesToState(state, loaded);
230
+ }
231
+ // Loads the `'next'` or `'previous'` page, and adds it to the end or the start. Returns `null`
232
+ // if there is no page in that direction. The page is added to the pages as they are when it
233
+ // arrives (and not as they were when the load started), so that a change made meanwhile by
234
+ // another action (for example, an item removed) is kept.
235
+ async _loadOneMore(old) {
236
+ const backward = this.which === 'previous';
237
+ const param = backward ? this._previousParamOf(old) : this._nextParamOf(old);
238
+ if (param == null)
239
+ return null;
240
+ const page = await this.loadPage(param, backward ? 'backward' : 'forward');
241
+ const addTo = backward ? addToStart : addToEnd;
242
+ return (state) => {
243
+ const current = this.getPagesFromState(state) ?? Pages.empty();
244
+ return this.applyPagesToState(state, this._withFlags(addTo(current.pages, page, this.maxPages), addTo(current.pageParams, param, this.maxPages)));
245
+ };
246
+ }
247
+ // Loads the pages from the first one: only the first page for a `'first'` (or when no page
248
+ // was loaded yet), or as many pages as the state has for a `'refresh'`. Each new page param
249
+ // comes from `nextPageParam`, so the pages stay consistent. Stops early when there are no
250
+ // more pages.
251
+ async _loadFromStart(old) {
252
+ const isRefresh = this.which === 'refresh';
253
+ const count = isRefresh ? Math.max(old.pages.length, 1) : 1;
254
+ let pages = [];
255
+ let params = [];
256
+ for (let i = 0; i < count; i++) {
257
+ let param;
258
+ if (i === 0) {
259
+ param = (isRefresh ? old.pageParams[0] : undefined) ?? this.initialPageParam();
260
+ }
261
+ else {
262
+ // Aborted meanwhile (by a newer `'first'` or `'refresh'`, or `store.abort`): doesn't
263
+ // load the other pages for nothing. The store ignores the result anyway.
264
+ if (this.isAborted)
265
+ throw (0, StoreException_1.kissAbort)('The load of the pages was aborted.');
266
+ const next = this._nextParamOf(new Pages(pages, params));
267
+ if (next == null)
268
+ break;
269
+ param = next;
270
+ }
271
+ const page = await this.loadPage(param, 'forward');
272
+ pages = addToEnd(pages, page, this.maxPages);
273
+ params = addToEnd(params, param, this.maxPages);
274
+ }
275
+ return this._withFlags(pages, params);
276
+ }
277
+ // Creates the `Pages`, computing `hasNextPage` and `hasPreviousPage` from the last and first pages.
278
+ _withFlags(pages, params) {
279
+ const result = new Pages(pages, params);
280
+ return result.copy({
281
+ hasNextPage: this._nextParamOf(result) != null,
282
+ hasPreviousPage: this._previousParamOf(result) != null,
283
+ });
284
+ }
285
+ _nextParamOf(pages) {
286
+ const last = pages.pages.length - 1;
287
+ if (last < 0)
288
+ return undefined;
289
+ return this.nextPageParam(pages.pages[last], pages.pages, pages.pageParams[last], pages.pageParams);
290
+ }
291
+ _previousParamOf(pages) {
292
+ if (pages.isEmpty || this.previousPageParam === undefined)
293
+ return undefined;
294
+ return this.previousPageParam(pages.pages[0], pages.pages, pages.pageParams[0], pages.pageParams);
295
+ }
296
+ // Aborts the other loads of the same list (same class and `pagesKeyParams()`) in progress.
297
+ _abortOtherLoads() {
298
+ for (const other of this.store.actionsInProgress()) {
299
+ if (other !== this && other instanceof this._type && (0, KissAction_1._isSameNonReentrantKey)(other.statusKey, this.statusKey))
300
+ other._abort(`A newer ${this.constructor.name} ('${this.which}') started loading the same pages.`);
301
+ }
302
+ }
303
+ get _type() {
304
+ return this.constructor;
305
+ }
306
+ /**
307
+ * For Kiss internal use only.
308
+ * @internal
309
+ */
310
+ _injectStore(_store) {
311
+ super._injectStore(_store);
312
+ if (!['first', 'next', 'previous', 'refresh'].includes(this.which))
313
+ throw new StoreException_1.StoreException(`Action ${this.constructor.name} is a LoadPages with an invalid \`which\`: ${String(this.which)}. ` +
314
+ `Use 'first', 'next', 'previous' or 'refresh'.`);
315
+ if (this.maxPages !== undefined && (!Number.isInteger(this.maxPages) || this.maxPages < 1))
316
+ throw new StoreException_1.StoreException(`Action ${this.constructor.name} is a LoadPages with an invalid \`maxPages\`: ${String(this.maxPages)}. ` +
317
+ 'Use a positive integer, or leave it undefined for no limit.');
318
+ if (this.nonReentrant)
319
+ throw new StoreException_1.StoreException(`Action ${this.constructor.name} is a LoadPages, which already runs one load per list at a time. ` +
320
+ 'Remove its `nonReentrant` property.');
321
+ if (this.ignoreOld)
322
+ throw new StoreException_1.StoreException(`Action ${this.constructor.name} is a LoadPages, which already aborts the older loads of the list. ` +
323
+ 'Remove its `ignoreOld` property.');
324
+ }
325
+ }
326
+ exports.LoadPages = LoadPages;
327
+ // Adds `item` to the end of `items`. If the result has more than `max` pages, drops the first.
328
+ function addToEnd(items, item, max) {
329
+ const result = [...items, item];
330
+ return (max !== undefined && result.length > max) ? result.slice(1) : result;
331
+ }
332
+ // Adds `item` to the start of `items`. If the result has more than `max` pages, drops the last.
333
+ function addToStart(items, item, max) {
334
+ const result = [item, ...items];
335
+ return (max !== undefined && result.length > max) ? result.slice(0, -1) : result;
336
+ }
@@ -1,120 +1,189 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PersistAction = exports.PersistException = exports.PersistorDummy = exports.PersistorPrinterDecorator = exports.Persistor = void 0;
4
- const KissAction_1 = require("./KissAction");
5
- const Store_1 = require("./Store");
6
- /**
7
- * Use it like this:
8
- *
9
- * ```ts
10
- * const persistor = new MyPersistor();
11
- *
12
- * let initialState = await persistor.readState();
13
- *
14
- * if (initialState === null) {
15
- * initialState = AppState.initialState();
16
- * await persistor.saveInitialState(initialState);
17
- * }
18
- *
19
- * const store = createStore<AppState>({
20
- * initialState: initialState,
21
- * persistor: persistor,
22
- * });
23
- * ```
24
- *
25
- * IMPORTANT: When the store is created with a Persistor, it assumes
26
- * the provided initial state was already persisted. Ensure this is the case.
27
- */
28
- class Persistor {
29
- /**
30
- * The default throttle is 2 seconds (2000 milliseconds).
31
- * Return `null` to turn off the throttle.
32
- */
33
- get throttle() {
34
- return 2000; // Default throttle is 2 seconds.
35
- }
36
- }
37
- exports.Persistor = Persistor;
38
- /**
39
- * A decorator to print persistor information to the console.
40
- * Use it like this:
41
- *
42
- * ```ts
43
- * const store = createStore<AppState>({
44
- * ...otherOptions,
45
- * persistor: new PersistorPrinterDecorator<AppState>(persistor),
46
- * });
47
- * ```
48
- */
49
- class PersistorPrinterDecorator {
50
- constructor(persistor) {
51
- this._persistor = persistor;
52
- }
53
- async readState() {
54
- Store_1.Store.log('Persistor: read state.');
55
- return this._persistor.readState();
56
- }
57
- async deleteState() {
58
- Store_1.Store.log('Persistor: delete state.');
59
- return this._persistor.deleteState();
60
- }
61
- async persistDifference(lastPersistedState, newState) {
62
- Store_1.Store.log(`Persistor: persist difference:
63
- lastPersistedState = ${lastPersistedState}
64
- newState = ${newState}`);
65
- return this._persistor.persistDifference(lastPersistedState, newState);
66
- }
67
- async saveInitialState(state) {
68
- Store_1.Store.log('Persistor: save initial state.');
69
- return this._persistor.saveInitialState(state);
70
- }
71
- get throttle() {
72
- return this._persistor.throttle;
73
- }
74
- }
75
- exports.PersistorPrinterDecorator = PersistorPrinterDecorator;
76
- /**
77
- * A dummy persistor.
78
- */
79
- class PersistorDummy {
80
- async readState() {
81
- return null;
82
- }
83
- async deleteState() {
84
- return;
85
- }
86
- async persistDifference(_lastPersistedState, _newState) {
87
- return;
88
- }
89
- async saveInitialState(_state) {
90
- return;
91
- }
92
- get throttle() {
93
- return null;
94
- }
95
- }
96
- exports.PersistorDummy = PersistorDummy;
97
- class PersistException extends Error {
98
- constructor(message) {
99
- super(message);
100
- this.name = 'PersistException';
101
- // Maintains proper stack trace for where our error was thrown (only available on V8).
102
- if (Error.captureStackTrace) {
103
- Error.captureStackTrace(this, PersistException);
104
- }
105
- }
106
- }
107
- exports.PersistException = PersistException;
108
- /**
109
- * An action that can be dispatched to force the Persistor to persist the state immediately.
110
- * It does not change the state.
111
- *
112
- * Note: This only works if the Persistor is waiting for the throttle period.
113
- * If the Persistor is currently persisting the state, this action will be ignored.
114
- */
115
- class PersistAction extends KissAction_1.KissAction {
116
- reduce() {
117
- return null;
118
- }
119
- }
120
- exports.PersistAction = PersistAction;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PersistAction = exports.PersistException = exports.PersistorDummy = exports.PersistorPrinterDecorator = exports.Persistor = void 0;
4
+ const KissAction_1 = require("./KissAction");
5
+ const Store_1 = require("./Store");
6
+ const utils_1 = require("./utils");
7
+ /**
8
+ * Use it like this:
9
+ *
10
+ * ```ts
11
+ * const store = createStore<AppState>({
12
+ * initialState: AppState.initialState(),
13
+ * persistor: new MyPersistor(),
14
+ * });
15
+ *
16
+ * await store.ready();
17
+ * store.dispatch(new InitAppAction());
18
+ * ```
19
+ *
20
+ * Do NOT read the state yourself before creating the store. When the store is created,
21
+ * Kiss calls `readState` once. If there is a saved state, it replaces the initial state in the
22
+ * store. If there is none, Kiss calls `saveInitialState` with the initial state.
23
+ *
24
+ * Until the persisted state is loaded, the store state is the `initialState`, which your UI can
25
+ * use while loading. Changes made to the state before `store.ready()` resolves may be
26
+ * overwritten by the persisted state, so wait for it before dispatching the actions that
27
+ * start your app.
28
+ */
29
+ class Persistor {
30
+ constructor() {
31
+ this._errors = [];
32
+ }
33
+ /**
34
+ * Function `saveInitialState` should save the given `state` to the persistence,
35
+ * replacing any previous state that was saved.
36
+ *
37
+ * The default implementation calls `persistDifference` with a `null` last persisted state.
38
+ *
39
+ * If this method throws, nothing is considered persisted, so the next call to
40
+ * `persistDifference` will receive a `null` last persisted state.
41
+ */
42
+ saveInitialState(state) {
43
+ return this.persistDifference(null, state);
44
+ }
45
+ /**
46
+ * The default throttle is 2 seconds (2000 milliseconds).
47
+ * Return `null` to turn off the throttle.
48
+ */
49
+ get throttle() {
50
+ return 2000; // Default throttle is 2 seconds.
51
+ }
52
+ /**
53
+ * If any error is thrown by `persistDifference`, you have the chance to further process
54
+ * it by using `wrapError`. Usually this is used to wrap the error inside another that
55
+ * better describes the failure. For example, you could turn a storage error into a
56
+ * `UserException`, so that it's shown to the user:
57
+ *
58
+ * ```ts
59
+ * wrapError(error: any) {
60
+ * return (error instanceof StorageError)
61
+ * ? new UserException('Could not save your data.', { hardCause: error })
62
+ * : error;
63
+ * }
64
+ * ```
65
+ *
66
+ * To ignore the error, return `null`. Note the state that failed to save is still NOT
67
+ * considered persisted.
68
+ *
69
+ * If instead of RETURNING an error you THROW an error inside `wrapError`, Kiss will use
70
+ * the thrown error instead of the original error. But it's recommended that you return it.
71
+ */
72
+ wrapError(error) {
73
+ return error;
74
+ }
75
+ /**
76
+ * Reports an error without throwing it. The error will be given to the store's
77
+ * `errorObserver` (with a `null` action), and if it's a `UserException`, it will be shown
78
+ * to the user. Other errors are thrown as unhandled promise rejections. Errors added here don't go through `wrapError`.
79
+ *
80
+ * This is useful in `readState`, `deleteState` and `saveInitialState`, when you can fix
81
+ * the problem yourself, but still want to let the user know about it.
82
+ */
83
+ addError(error) {
84
+ this._errors.push(error);
85
+ }
86
+ /**
87
+ * Returns the first error added with `addError`, and removes it.
88
+ * Returns `null` if there are no errors. Used by Kiss.
89
+ */
90
+ getAndRemoveFirstError() {
91
+ return (this._errors.length === 0) ? null : this._errors.shift();
92
+ }
93
+ }
94
+ exports.Persistor = Persistor;
95
+ /**
96
+ * A decorator to print persistor information to the console.
97
+ * Use it like this:
98
+ *
99
+ * ```ts
100
+ * const store = createStore<AppState>({
101
+ * ...otherOptions,
102
+ * persistor: new PersistorPrinterDecorator<AppState>(persistor),
103
+ * });
104
+ * ```
105
+ */
106
+ class PersistorPrinterDecorator extends Persistor {
107
+ constructor(persistor) {
108
+ super();
109
+ this._persistor = persistor;
110
+ }
111
+ async readState() {
112
+ Store_1.Store.log('Persistor: read state.');
113
+ return this._persistor.readState();
114
+ }
115
+ async deleteState() {
116
+ Store_1.Store.log('Persistor: delete state.');
117
+ return this._persistor.deleteState();
118
+ }
119
+ async persistDifference(lastPersistedState, newState) {
120
+ // The states are only described when logging is on. Describing them never throws.
121
+ Store_1.Store._logLazy(() => `Persistor: persist difference:
122
+ lastPersistedState = ${(0, utils_1.describeValue)(lastPersistedState)}
123
+ newState = ${(0, utils_1.describeValue)(newState)}`);
124
+ return this._persistor.persistDifference(lastPersistedState, newState);
125
+ }
126
+ async saveInitialState(state) {
127
+ Store_1.Store.log('Persistor: save initial state.');
128
+ return this._persistor.saveInitialState(state);
129
+ }
130
+ get throttle() {
131
+ return this._persistor.throttle;
132
+ }
133
+ wrapError(error) {
134
+ return this._persistor.wrapError(error);
135
+ }
136
+ addError(error) {
137
+ this._persistor.addError(error);
138
+ }
139
+ getAndRemoveFirstError() {
140
+ return this._persistor.getAndRemoveFirstError();
141
+ }
142
+ }
143
+ exports.PersistorPrinterDecorator = PersistorPrinterDecorator;
144
+ /**
145
+ * A dummy persistor.
146
+ */
147
+ class PersistorDummy extends Persistor {
148
+ async readState() {
149
+ return null;
150
+ }
151
+ async deleteState() {
152
+ return;
153
+ }
154
+ async persistDifference(_lastPersistedState, _newState) {
155
+ return;
156
+ }
157
+ async saveInitialState(_state) {
158
+ return;
159
+ }
160
+ get throttle() {
161
+ return null;
162
+ }
163
+ }
164
+ exports.PersistorDummy = PersistorDummy;
165
+ class PersistException extends Error {
166
+ constructor(message) {
167
+ super(message);
168
+ this.name = 'PersistException';
169
+ // Maintains proper stack trace for where our error was thrown (only available on V8).
170
+ if (Error.captureStackTrace) {
171
+ Error.captureStackTrace(this, PersistException);
172
+ }
173
+ }
174
+ }
175
+ exports.PersistException = PersistException;
176
+ /**
177
+ * An action that can be dispatched to force the Persistor to persist the state immediately,
178
+ * ignoring the throttle period. It does not change the state.
179
+ *
180
+ * If the Persistor is currently persisting the state, the state is persisted as soon as it
181
+ * finishes (still ignoring the throttle). It does nothing if the state is already persisted,
182
+ * or if the Persistor is paused.
183
+ */
184
+ class PersistAction extends KissAction_1.KissAction {
185
+ reduce() {
186
+ return null;
187
+ }
188
+ }
189
+ exports.PersistAction = PersistAction;