-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathOverviewModel.js
More file actions
265 lines (233 loc) · 8.47 KB
/
Copy pathOverviewModel.js
File metadata and controls
265 lines (233 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* @license
* Copyright CERN and copyright holders of ALICE O2. This software is
* distributed under the terms of the GNU General Public License v3 (GPL
* Version 3), copied verbatim in the file "COPYING".
*
* See http://alice-o2.web.cern.ch/license for full licensing information.
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
import { buildUrl, Observable, RemoteData } from '/js/src/index.js';
import { ObservableData } from '../utilities/ObservableData.js';
import { PaginatedRemoteDataSource } from '../utilities/fetch/PaginatedRemoteDataSource.js';
import { PaginationModel } from '../components/Pagination/PaginationModel.js';
import { SortModel } from '../components/common/table/SortModel.js';
/**
* Interface of a model representing an overview page state
*
* @interface OverviewModel
*/
/**
* @property {PaginationModel} OverviewModel#pagination pagination model of the overview
*/
/**
* Base model for an overview page
*
* @template T the type of data displayed in the overview page
*/
export class OverviewPageModel extends Observable {
/**
* Constructor
*/
constructor() {
super();
this._warnings = new Map();
this._sortModel = new SortModel();
this._sortModelCallback = () => {
this._pagination.silentlySetCurrentPage(1);
this.load();
};
this._sortModel.observe(this._sortModelCallback);
this._sortModel.visualChange$.bubbleTo(this);
// Single page data handling
this._pagination = new PaginationModel();
this._pagination.observe(() => this.load());
this._pagination.itemsPerPageSelector$.observe(() => this.notify());
const dataSourceObservable = ObservableData.builder().initialValue(RemoteData.loading()).build();
dataSourceObservable.observe(() => this.parseApiPaginatedRemoteData(dataSourceObservable.getCurrent()));
this._dataSource = new PaginatedRemoteDataSource();
this._dataSource.pipe(dataSourceObservable);
this._item$ = ObservableData.builder().initialValue(RemoteData.loading()).build();
this._item$.bubbleTo(this);
// All data handling
const allDataSourceObservable = ObservableData.builder().initialValue(RemoteData.loading()).build();
allDataSourceObservable.observe(() => this.parseApiNotPaginatedRemoteData(allDataSourceObservable.getCurrent()));
this._allDataSource = new PaginatedRemoteDataSource();
this._allDataSource.pipe(allDataSourceObservable);
this._allItems$ = ObservableData.builder().initialValue(RemoteData.loading()).build();
this._allItems$.bubbleTo(this);
/**
* @type {ObservableData<TableConfiguration>}
*/
this._displayOptions = new ObservableData({
horizontalScrollEnabled: false,
freezeFirstColumn: false,
});
}
/**
* Return the root endpoint for the model to use to fetch data
*
* @return {string} the endpoint
* @abstract
*/
getRootEndpoint() {
throw new Error('Abstract function call');
}
/**
* Reset this model to its default
*
* @returns {void}
*/
reset() {
this._item$.setCurrent(RemoteData.notAsked());
this._pagination.reset();
this._warnings.clear();
}
/**
* Parse the API remote data to extract the list of items to display and update the pagination
*
* @param {RemoteData<{items: T[], totalCount: number}, *>} remoteData the API remote data
* @return {void}
*/
parseApiPaginatedRemoteData(remoteData) {
/*
* When fetching data, to avoid concurrency issues, save a flag stating if the fetched data should be concatenated with the current one
* (infinite scroll) or if they should replace them
*/
const keepExisting = this._pagination.currentPage > 1 && this._pagination.isInfiniteScrollEnabled;
remoteData.match({
NotAsked: () => this._item$.setCurrent(RemoteData.notAsked()),
Loading: () => this._pagination.isInfiniteScrollEnabled ? null : this._item$.setCurrent(RemoteData.loading()),
Success: ({ items, totalCount }) => {
const concatenateWith = keepExisting ? this.items.match({
Success: (payload) => payload,
Loading: () => [],
NotAsked: () => [],
Failure: () => [],
}) : [];
this._pagination.itemsCount = totalCount;
this._item$.setCurrent(RemoteData.success([...concatenateWith, ...this.processItems(items)]));
},
Failure: (error) => this._item$.setCurrent(RemoteData.failure(error)),
});
}
/**
* Parse the API remote data to extract the list of items
*
* @param {RemoteData<{items: T[], totalCount: number}, *>} remoteData the API remote data
* @return {void}
*/
parseApiNotPaginatedRemoteData(remoteData) {
remoteData.match({
NotAsked: () => this._allItems$.setCurrent(RemoteData.notAsked()),
Loading: () => this._allItems$.setCurrent(RemoteData.loading()),
Success: ({ items }) => {
this._allItems$.setCurrent(RemoteData.success(this.processItems(items)));
},
Failure: (error) => this._allItems$.setCurrent(RemoteData.failure(error)),
});
}
/**
* Apply a processing on each provided items and return the result
*
* @param {T[]} items the items to process
* @return {T[]} The list of processed items
*/
processItems(items) {
return items;
}
/**
* Fetch all the relevant items from the API
* it takes into account pagination parameters, but also reset not-paginated observable data
*
* @return {Promise<void>} void
*/
async load() {
const params = await this.getLoadParameters();
this._allItems$.setCurrent(RemoteData.notAsked());
await this._dataSource.fetch(buildUrl(this.getRootEndpoint(), params));
}
/**
* Fetch all the relevant items from the API
* it does not take into account pagination parameters
*
* @return {Promise<void>} void
*/
async loadAll() {
await this._allDataSource.fetch(this.getRootEndpoint());
}
/**
* Return the query params to use to get load the overview data
*
* @return {Promise<Object<string, number|string|number[]|string[]>>} the params
*/
async getLoadParameters() {
const params = {
'page[offset]': this._pagination.firstItemOffset,
'page[limit]': this._pagination.itemsPerPage,
};
const { appliedOn: sortOn, appliedDirection: sortDirection } = this._sortModel;
if (sortOn && sortDirection) {
params[`sort[${sortOn}]`] = sortDirection;
}
return params;
}
/**
* Return the current items remote data
*
* @return {RemoteData<T[]>} the items
*/
get items() {
return this._item$.getCurrent();
}
/**
* Returns the overview pagination
*
* @return {PaginationModel} the pagination
*/
get pagination() {
return this._pagination;
}
/**
* Patch overview display configuration
* @param {Partial<TableConfiguration>} patch patch to be applied to current configuration
* @return {void}
*/
patchDisplayOptions(patch) {
this._displayOptions.setCurrent({ ...this.displayOptions, ...patch });
}
/**
* Get overview display configuration
* @return {Partial<TableConfiguration>} table configuration
*/
get displayOptions() {
return this._displayOptions.getCurrent();
}
/**
* Returns the model handling the overview page table sort
*
* @return {SortModel} the sort model
*/
get sortModel() {
return this._sortModel;
}
/**
* State whther some data was successfuly fetched
*
* @return {boolean} true if any data was successfuly fetched, false otherwise
*/
hasAnyData() {
return this._item$.getCurrent().match({ Success: ({ length = 0 } = {}) => length > 0, Other: () => false });
}
/**
* Returns the warnings object
*
* @return {object} the warning model
*/
get warnings() {
return this._warnings;
}
}