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