/
models-table-server-paginated.ts
352 lines (325 loc) · 10.1 KB
/
models-table-server-paginated.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { isBlank, isNone } from '@ember/utils';
import { debounce } from '@ember/runloop';
import ModelsTable from './models-table';
import ModelsTableColumn from '../utils/emt/emt-column';
import { SortConstants } from '../constants/sort-constants';
import { type ModelsTableServerPaginatedArgs } from '../interfaces/components/models-table-server-paginated-args.interface';
import { type FilterQueryParameters } from '../interfaces/filter-query-parameters.interface';
import { type DataRequestQuery } from '../interfaces/data-request-query.interface';
/**
* Table-component with pagination, sorting and filtering.
*
* It should be used when pagination, filtering and sorting are done on the server-side. Otherwise, {@link Core.ModelsTable | ModelsTable} should be used.
*
* This component extends the base models-table component. For the end user, it can be used (nearly) the same:
*
* ```html
* <ModelsTableServerPaginated
* @data={{this.data}}
* @columns={{this.columns}}
* @themeInstance={{this.themeInstance}}
* @doQuery={{this.doQuery}}
* @itemsCount={{this.itemsCount}}
* @pagesCount={{this.pagesCount}}
* />
* ```
*
* Usage with block context:
*
* ```html
* <ModelsTableServerPaginated
* @data={{this.data}}
* @columns={{this.columns}}
* @themeInstance={{this.themeInstance}}
* @doQuery={{this.doQuery}}
* @itemsCount={{this.itemsCount}}
* @pagesCount={{this.pagesCount}}
* as |MT|>
* <MT.GlobalFilter />
* <MT.DataGroupBySelect />
* <MT.ColumnsDropdown />
* <MT.Table />
* <MT.Footer />
* </ModelsTableServerPaginated>
* ```
*
* Here `doQuery` is an action-handler used when user interacts with table by changing page number, page size, global or column filter, sorting etc.
*
* `itemsCount` and `pagesCount` show how many rows are in the table's page and how many pages are overall.
*
* ModelsTableServerPaginated yields same components, actions and properties as a ModelsTable does. Check its docs for more info.
*
* Check own docs for each component to get detailed info.
*
* ModelsTableServerPaginated has a lot of options you may configure, but there are six required properties called `data`, `columns`, `themeInstance`, `doQuery`, `itemsCount` and `pagesCount`.
*
* A few things to notice:
*
* - When using `filterWithSelect` for a column, you must use `predefinedFilterOptions`, because the automatic loading of possible filter values cannot work here.
* - There is a new optional field `filteredBy` for columns, which works much like `sortedBy`: if set, this field will be used as query parameter, otherwise it will use the `propertyName`.
* - Sorting will not use multipleColumnSorting, it will only sort by one column.
* - If you set `sortedBy: false` on a column, sorting will be disabled for this column.
*
* There are a couple of things which can be configured to adapt to your API:
*
* ```js
* // The time to wait until new data is actually loaded.
* // This can be tweaked to avoid making too many server requests.
* debounceDataLoadTime: 500,
*
* // The query parameters to use for server side filtering / querying.
* filterQueryParameters: {
* globalFilter: 'search',
* sort: 'sort',
* sortDirection: 'sortDirection',
* page: 'page',
* pageSize: 'pageSize'
* },
* ```
*
* This default configuration would try to get the total page count from `model.get('meta.pagesCount')` and the total item count from `model.get('meta.itemsCount')`, and would then go on to build the following query:
*
* ```js
* columns: [
* {
* propertyName: 'name',
* filteredBy: 'model_name'
* }
* ]
*
* // after searching globally for "searchtexthere"
* // and in the name column for "filterforname",
* // and going to page 2,
* // the following query would be built:
* ?page=2&pageSize=50&search=searchtexthere&sort=name&sortDirection=ASC&model_name=filterforname
* ```
*/
export default class ModelsTableServerPaginated extends ModelsTable<ModelsTableServerPaginatedArgs> {
/**
* The time to wait until new data is actually loaded.
* This can be tweaked to avoid making too many server requests.
*
* @default 500
*/
protected get debounceDataLoadTime(): number {
return this.args.debounceDataLoadTime ?? 500;
}
@tracked
protected _filterQueryParameters = {
globalFilter: 'search',
sort: 'sort',
sortDirection: 'sortDirection',
page: 'page',
pageSize: 'pageSize',
};
/**
* The query parameters to use for server side filtering / querying.
*/
protected get filterQueryParameters(): FilterQueryParameters {
return this.args.filterQueryParameters ?? this._filterQueryParameters;
}
get filteredContent(): any {
return this.args.data;
}
/**
* For server side filtering, arrangedContent is same as the filtered content
*/
get arrangedContent(): any {
return this.filteredContent;
}
/**
* For server side filtering, visibleContent is same as the filtered content
*/
get visibleContent(): any {
return this.arrangedContent;
}
get arrangedContentLength(): number {
return this.args.itemsCount ?? 0;
}
get pagesCount(): number {
return this.args.pagesCount ?? 1;
}
/**
* The index of the last item that is currently being shown.
*/
get lastIndex(): number {
const pageMax = parseInt(`${this.pageSize}`, 10) * this.currentPageNumber;
return Math.min(pageMax, this.arrangedContentLength);
}
/**
* This function actually loads the data from the server
*/
protected _loadData(): any {
let query = Object.assign({}, this.args.query || {}) as DataRequestQuery;
// Add pagination information
query[this.filterQueryParameters.page] = this.currentPageNumber;
query[this.filterQueryParameters.pageSize] = this.pageSize;
// Add sorting information
if (this.sortProperties && this.sortProperties.length) {
if (this.multipleColumnsSorting) {
query = this.multipleColumnsSortingWrapper(query, this.sortProperties);
} else {
if (this.sortProperties[0]) {
const [sortBy, sortDirection] = this.sortProperties[0].split(':');
query = this.singleColumnSortingWrapper(
query,
sortBy || '',
sortDirection || '',
);
}
}
} else {
delete query[this.filterQueryParameters.sort];
delete query[this.filterQueryParameters.sortDirection];
}
// Add global filter
const globalFilter = this.filterQueryParameters.globalFilter;
if (this.filterString) {
query[globalFilter] = this.filterString;
} else {
delete query[globalFilter];
}
// Add per-column filter
if (this.useFilteringByColumns) {
this.processedColumns.forEach((column) => {
this.setQueryFilter(
query,
column,
column.filterField,
column.filterString,
);
});
}
this.isLoading = true;
this.isError = false;
return this.args
.doQuery(query)
.then(() => {
this.isLoading = false;
this.isError = false;
})
.catch(() => {
this.isLoading = false;
this.isError = true;
});
}
/**
* Actually set the filter on a query.
* This can be overwritten for special case handling.
* Note that this will mutate the given query object!
*/
protected setQueryFilter(
query: DataRequestQuery,
_: ModelsTableColumn,
filterTitle?: string,
filter?: string,
): void {
if (!isBlank(filter)) {
if (filterTitle) {
query[filterTitle] = filter;
}
} else {
if (filterTitle) {
delete query[filterTitle];
}
}
}
/**
* Wrapper for sorting query when single column sorting is used
*/
protected singleColumnSortingWrapper(
query: DataRequestQuery,
sortBy: string,
sortDirection: string,
): DataRequestQuery {
query[this.filterQueryParameters.sort] = sortBy;
query[this.filterQueryParameters.sortDirection] = sortDirection;
return query;
}
/**
* Wrapper for sorting query when multi columns sorting is used
*/
protected multipleColumnsSortingWrapper(
query: DataRequestQuery,
sortProperties: string[],
): DataRequestQuery {
query[this.filterQueryParameters.sort] = sortProperties
.map((sortProp) => {
const [prop, direction] = sortProp.split(':');
const sign = (direction || '').toLowerCase() === 'desc' ? '-' : '';
return `${sign}${prop}`;
})
.join(',');
return query;
}
protected _loadDataOnce(): void {
debounce(this, this._loadData, this.debounceDataLoadTime);
}
constructor(owner: unknown, args: ModelsTableServerPaginatedArgs) {
super(owner, args);
this.multipleColumnsSorting = false;
}
/**
* @event sort
*/
@action
sort(column: ModelsTableColumn): void {
if (isNone(column.sortField)) {
return;
}
const currentSorting = column.sorting || SortConstants.none;
const newSorting = this.sortMap[currentSorting];
if (this.multipleColumnsSorting) {
this._multiColumnsSorting(column, column.sortField, newSorting);
} else {
this._singleColumnSorting(column, column.sortField, newSorting);
}
this.userInteractionObserver();
this._loadDataOnce();
}
/**
* @event changeColumnFilter
*/
@action
changeColumnFilter(
newColumnFilterValue: string,
column: ModelsTableColumn,
): void {
super.changeColumnFilter(newColumnFilterValue, column);
this._loadDataOnce();
}
/**
* @event changeGlobalFilter
*/
@action
changeGlobalFilter(newGlobalFilterValue: string): void {
super.changeGlobalFilter(newGlobalFilterValue);
this._loadDataOnce();
}
/**
* @event changePageSize
*/
@action
changePageSize(newPageSize: string): void {
super.changePageSize(newPageSize);
this._loadDataOnce();
}
/**
* @event goToPage
*/
@action
goToPage(pageNumber: number): void {
super.goToPage(pageNumber);
this._loadDataOnce();
}
/**
* @event clearFilters
*/
@action
clearFilters(): void {
super.clearFilters();
this._loadDataOnce();
}
}