-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.component.ts
435 lines (415 loc) · 10.3 KB
/
table.component.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//our root app component
import {Component, Input, OnInit} from '@angular/core';
import {Http, Response, RequestOptions, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
/**
* Order type
*/
export class Order {
by: string;
mod: string;
}
export class Filter {
property: string;
operator: string;
value: any;
}
/**
* Metadata added to objects in the list
*/
export class ListObject {
public $selected: boolean;
};
/**
* Table component
*
* NOTE: Transclude thead and tbody
*
* #### Example
*
* ```html
* <vs-table uri="/api/v1/users" #list>
* <thead>
* <tr>
* <th>Id</th>
* <th>Name</th>
* </tr>
* </thead>
* <tbody>
* <tr
* *ngFor="let row of list.list; let i = index;"
* >
* <td>{{row.id}}</td>
* <td>{{row.name}}</td>
* </tr>
* </tbody>
* </vs-table>
* ```
*/
@Component({
selector: 'vs-table',
template: `
<div>
<table class="table table-striped">
<ng-content select="thead"></ng-content>
<ng-content select="tbody"></ng-content>
<tfoot>
<tr>
<td colspan="999">
<nav aria-label="Items per page" class="float-right">
<div class="btn-group" role="group" aria-label="Items per page">
<button type="button" class="btn btn-secondary"
[ngClass]="{'active': limit == 10}"
(click)="setLimit(10)">10</button>
<button type="button" class="btn btn-secondary"
[ngClass]="{'active': limit == 20}"
(click)="setLimit(20)">20</button>
<button type="button" class="btn btn-secondary"
[ngClass]="{'active': limit == 50}"
(click)="setLimit(50)">50</button>
</div>
</nav>
<nav aria-label="List navigation">
<ul class="pagination">
<li class="page-item" [ngClass]="{'disabled': currentPage == 0}">
<a class="page-link" (click)="previousPage()">
<i class="fa fa-angle-double-left" aria-hidden="true"></i>
</a>
</li>
<li class="page-item"
[ngClass]="{'active': page == currentPage}"
*ngFor="let page of pages">
<a class="page-link"
(click)="setPage(page)">{{page + 1}}</a>
</li>
<li class="page-item" [ngClass]="{'disabled': currentPage == pageCount - 1}">
<a class="page-link" (click)="nextPage()">
<i class="fa fa-angle-double-right" aria-hidden="true"></i>
</a>
</li>
</ul>
</nav>
</td>
</tr>
<tr>
<td colspan="999">
<span>Total items: {{totalCount}}</span>
<span>Selected: {{selectedCount}}</span>
</td>
</tr>
</tfoot>
</table>
<!--
<pre>
filters: {{filters | json}}
order: {{order | json}}
</pre>
-->
</div>
`,
})
export class Table implements OnInit {
// inputs
/**
* Api URL
*/
@Input() uri: string;
/**
* Microseconds before trigger the refresh
*/
@Input() refreshDelay: number = 1250;
/**
* Don't do the first request
*/
@Input() starStopped: boolean = false;
/**
* Current/Initial order
*/
@Input() order: Order = {
'by': null,
mod: 'ASC'
};
/**
* Current/Initial filters
* ### Example
* ```json
* {
* propertyName: {
* operator: "",
* value: xx
* }
* }
* ```
*/
@Input() filters: Filter[] = [];
/**
* list of objects from API
*/
list: ListObject[] = [];
/**
* cloned list for use it at getModified
*/
original: ListObject[] = [];
totalCount: number;
limit: number = 10;
pages: Number[] = [];
currentPage: number = 0;
pageCount: number = 1;
selectedCount: number = 0; // cache this value
refreshTimeout: number = null;
constructor(protected http: Http) {}
/*
* refresh unless starStopped
*/
ngOnInit(): void {
if (!this.starStopped) {
this.refresh();
}
}
/**
* get filter by property
*/
getFilter(property: string): Filter|null {
for (let i: number = 0; i < this.filters.length; ++i) {
if (this.filters[i].property === property) {
return this.filters[i];
}
}
return null;
}
/**
* Remove filter by property
*/
removeFilter(property: string): boolean {
for (let i: number = 0; i < this.filters.length; ++i) {
if (this.filters[i].property === property) {
this.filters.splice(i, 1);
return true;
}
}
return false;
}
/*
* Set/remove filter and queueRefresh
* Note only 'IS NULL' operator allow value to be null
* the rest just remove the filter.
*/
setFilter(property: string, operator: string, value: any, allowNull: boolean = false): void {
// search property
let idx: number = -1;
for (let i: number = 0; i < this.filters.length; ++i) {
if (this.filters[i].property === property) {
idx = i;
}
}
// not found create
if (idx === -1) {
if (value === null && !allowNull) {
return;
}
if (value === null && allowNull) {
this.filters.push({
property: property,
operator: operator,
value: null // not really needed here
});
} else {
this.filters.push({
property: property,
operator: operator,
value: value
});
}
} else {
// update or delete ? :)
if (
(value === null && !allowNull) ||
(typeof value === 'string' && !value.length)
) {
this.filters.splice(idx, 1);
} else {
let obj: Filter = this.filters[idx];
obj.operator = operator;
obj.value = value;
}
}
this.queueRefresh();
}
/**
* Set order and queueRefresh
*/
setOrder(prop: string): void {
if (this.order.by === prop) { // toggle!
this.order.mod = this.order.mod === 'ASC' ? 'DESC' : 'ASC';
} else {
this.order.by = prop;
this.order.mod = 'ASC';
}
this.queueRefresh();
}
/**
* Gentle refresh with debounce
*/
queueRefresh(): void { // debounce
clearTimeout(this.refreshTimeout);
this.refreshTimeout = window.setTimeout(() => {
this.refresh();
}, this.refreshDelay);
}
/**
* Get HTTP/CSV Observable, you should handle how to save it
*/
getCSV(): Observable<Response> {
return this.getHttp(new RequestOptions({
headers: new Headers({ 'Content-Type': 'text/csv'
})}));
/*
.subscribe(response => {
console.log(response);
});
*/
}
/*
* Encode limit, page, filter and order into a string to append to query
* Override if you need a custom format.
*/
buildOptionsQuery(): string {
return 'query=' + JSON.stringify({
limit: this.limit,
page: this.currentPage,
filters: this.filters,
order: this.order
});
}
/*
* Parse server response
* Override if your server response has a custom format.
*/
parseResponse(response: Response): void {
this.list = response.json();
// clean & fast clone :)
this.original = JSON.parse(JSON.stringify(this.list));
var t: string = response.headers.get('X-Total-Count');
if (t == null) {
throw new Error('X-Total-Count header is required');
}
this.totalCount = parseInt(t, 10);
//this.currentPage = parseInt(response.headers.get('X-Page'), 10);
//this.limit = parseInt(response.headers.get('X-Limit'), 10);
this.updatePagination();
}
/**
* Get HTTP Observable
* This is used for normal list (json) or CSV variant.
*/
getHttp(options: RequestOptions = undefined): Observable<Response> {
return this
.http
.get(this.uri + '?' + this.buildOptionsQuery(), options);
}
/**
* Refresh the list from the server
*/
refresh(): any {
window.clearTimeout(this.refreshTimeout); // also clear here, because pagination it's instant
this.refreshTimeout = null;
return this.getHttp()
.subscribe(
response => {
this.parseResponse(response);
},
err => console.log(err)
);
}
/**
* update pagination
*/
updatePagination(): void {
this.pageCount = Math.ceil(this.totalCount / this.limit);
this.pages = Array(this.pageCount).fill(0).map((x, i) => i);
}
/**
* Go to next page and refresh
*/
nextPage(): void {
++this.currentPage;
this.refresh();
}
/**
* Go to previous page and refresh
*/
previousPage(): void {
--this.currentPage;
this.refresh();
}
/**
* Set current page and refresh
*/
setPage(page: number): void {
this.currentPage = page;
this.refresh();
}
/**
* Remove given row from list
*/
removeRow(index: number): void {
this.list.splice(index, 1);
}
/**
* Set limit and refresh
*/
setLimit(limit: number): void {
this.limit = limit;
this.refresh();
}
/**
* Toggle row
*/
selectRow(index: number): void {
if (index >= this.list.length) {
throw new Error('out of bounds');
}
this.list[index].$selected = !this.list[index].$selected;
this.selectedCount = this.getSelection().length;
}
/**
* Is given row selected?
*/
isSelected(index: number): boolean {
if (index >= this.list.length) {
throw new Error('out of bounds');
}
return this.list[index].$selected;
}
/**
* Get selected object list
*/
getSelection(): Object[] {
return this.list.filter((row: ListObject) => {
return row.$selected;
});
}
/**
* Reset list to original values
*/
restore(): void {
this.list = JSON.parse(JSON.stringify(this.original));
}
/**
* Get modified values list
*/
getModified(identifier: string): Object[] {
var modified: Object[] = [];
for (var i: number = 0; i < this.list.length; ++i) {
for (var j: number = 0; j < this.original.length; ++j) {
if (this.list[i][identifier] === this.original[j][identifier]) {
if (JSON.stringify(this.list[i]) !== JSON.stringify(this.original[j])) {
modified.push(this.list[i]);
}
break;
}
}
}
return modified;
}
}